Best way to detect that HTML5 is not supp

2019-01-03 12:17发布

The standard way to deal with situations where the browser does not support the HTML5 <canvas> tag is to embed some fallback content like:

<canvas>Your browser doesn't support "canvas".</canvas>

But the rest of the page remains the same, which may be inappropriate or misleading. I'd like some way of detecting canvas non-support so that I can present the rest of my page accordingly. What would you recommend?

7条回答
爷的心禁止访问
2楼-- · 2019-01-03 12:18

You can use canisuse.js script to detect if your browsers supports canvas or not

caniuse.canvas()
查看更多
smile是对你的礼貌
3楼-- · 2019-01-03 12:30

Why not try modernizr ? It's a JS library that provides detection capability.

Quote:

Have you ever wanted to do if-statements in your CSS for the availability of cool features like border-radius? Well, with Modernizr you can accomplish just that!

查看更多
混吃等死
4楼-- · 2019-01-03 12:31

There may be a gotcha here- some clients do not support all canvas methods.

var hascanvas= (function(){
    var dc= document.createElement('canvas');
    if(!dc.getContext) return 0;
    var c= dc.getContext('2d');
    return typeof c.fillText== 'function'? 2: 1;
})();

alert(hascanvas)
查看更多
唯我独甜
5楼-- · 2019-01-03 12:37
try {
    document.createElement("canvas").getContext("2d");
    alert("HTML5 Canvas is supported in your browser.");
} catch (e) {
    alert("HTML5 Canvas is not supported in your browser.");
}
查看更多
看我几分像从前
6楼-- · 2019-01-03 12:38

This is the technique used in Modernizr and basically every other library that does canvas work:

function isCanvasSupported(){
  var elem = document.createElement('canvas');
  return !!(elem.getContext && elem.getContext('2d'));
}

Since your question was for detection when it's not supported, I recommend using it like so:

if (!isCanvasSupported()){ ...
查看更多
淡お忘
7楼-- · 2019-01-03 12:41

I usually run a check for getContext when I create my canvas object.

(function () {
    var canvas = document.createElement('canvas'), context;
    if (!canvas.getContext) {
        // not supported
        return;
    }

    canvas.width = 800;
    canvas.height = 600;
    context = canvas.getContext('2d');
    document.body.appendChild(canvas);
}());

If it is supported, then you can continue the canvas setup and add it to the DOM. This is a simple example of Progressive Enhancement, which I (personally) prefer over Graceful Degradation.

查看更多
登录 后发表回答