Javascript 检测不支持 HTML5 <canvas> 的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2745432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to detect that HTML5 <canvas> is not supported
提问by brainjam
The standard way to deal with situations where the browser does not support the HTML5 <canvas>tag is to embed some fallback content like:
处理浏览器不支持 HTML5<canvas>标签情况的标准方法是嵌入一些后备内容,例如:
<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?
但页面的其余部分保持不变,这可能是不适当的或误导性的。我想要某种检测画布不支持的方法,以便我可以相应地呈现我页面的其余部分。你会推荐什么?
回答by Paul Irish
This is the technique used in Modernizr and basically every other library that does canvas work:
这是在 Modernizr 和基本上所有其他可以使用画布的库中使用的技术:
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
Since your question was for detection when it's notsupported, I recommend using it like so:
由于您的问题是检测时,它不支持,我建议使用它像这样:
if (!isCanvasSupported()){ ...
回答by Andy E
There are two popular methods of detecting canvas support in browsers:
在浏览器中检测画布支持有两种流行的方法:
Matt's suggestionof checking for the existence of
getContext, also used in a similar fashion by the Modernizr library:var canvasSupported = !!document.createElement("canvas").getContext;Checking the existence of the
HTMLCanvasElementinterface, as defined by the WebIDLand HTMLspecifications.?This approach was also recommended in a blog post from the IE 9 team.var canvasSupported = !!window.HTMLCanvasElement;
马特关于检查 存在的建议
getContext,也被 Modernizr 库以类似的方式使用:var canvasSupported = !!document.createElement("canvas").getContext;检查
HTMLCanvasElement接口是否存在,如WebIDL和HTML规范所定义的那样。IE 9 团队的博客文章中也推荐了这种方法。var canvasSupported = !!window.HTMLCanvasElement;
My recommendation is a variation of the latter (see Additional Notes), for several reasons:
我的建议是后者的变体(请参阅附加说明),原因如下:
- Every known browser supporting canvas ― including IE 9 ― implements this interface;
- It's more concise and instantly obvious what the code is doing;
- The
getContextapproach is significantly sloweracross all browsers, because it involves creating an HTML element.?This is not ideal when you need to squeeze as much performance as possible (in a library like Modernizr, for example).
- 每个已知的支持画布的浏览器——包括 IE 9——都实现了这个接口;
- 代码在做什么更简洁,一目了然;
- 该
getContext方法在所有浏览器上都明显变慢,因为它涉及创建 HTML 元素。当您需要尽可能多地压缩性能时(例如在像 Modernizr 这样的库中),这并不理想。
There are no noticeable benefits to using the first method.?Both approaches can be spoofed, but this not likely to happen by accident.
使用第一种方法没有明显的好处。这两种方法都可以被欺骗,但这不太可能是偶然发生的。
Additional Notes
补充说明
It may still be necessary to check that a 2D context can be retrieved.?Reportedly, some mobile browsers can return true for both above checks, but return nullfor .getContext('2d').?This is why Modernizr also checks the result of .getContext('2d').? However, WebIDL & HTML ― again ― gives us another better, fasteroption:
它仍可能需要检查2D背景可以retrieved.?Reportedly,一些移动浏览器可以同时为上述检查返回true,而是返回null了.getContext('2d')?这就是为什么Modernizr的检查也的结果.getContext('2d')?然而,WebIDL 和 HTML —— 再次 —— 为我们提供了另一个更好、更快的选择:
var canvas2DSupported = !!window.CanvasRenderingContext2D;
Notice that we can skip checking for the canvas element entirely and go straight to checking for 2D rendering support. The CanvasRenderingContext2Dinterface is also part of the HTML specification.
请注意,我们可以完全跳过检查 canvas 元素,直接检查 2D 渲染支持。该CanvasRenderingContext2D界面也是 HTML 规范的一部分。
You mustuse the getContextapproach for detecting WebGLsupport because, even though the browser may support the WebGLRenderingContext, getContext()may return nullif the browser is unable to interface with the GPU due to driver issues and there is no software implementation. In this case, checking for the interface first allows you to skip checking for getContext:
您必须使用检测 WebGL支持的getContext方法,因为即使浏览器可能支持WebGLRenderingContext,如果浏览器由于驱动程序问题而无法与 GPU 交互并且没有软件实现,getContext()也可能返回null。在这种情况下,首先检查接口允许您跳过检查getContext:
var cvsEl, ctx;
if (!window.WebGLRenderingContext)
window.location = "http://get.webgl.org";
else {
cvsEl = document.createElement("canvas");
ctx = cvsEl.getContext("webgl") || cvsEl.getContext("experimental-webgl");
if (!ctx) {
// Browser supports WebGL, but cannot create the context
}
}
Performance Comparison
性能比较
Performance of the getContextapproach is 85-90% slower in Firefox 11 and Opera 11 and about 55% slower in Chromium 18.
该getContext方法的性能在 Firefox 11 和 Opera 11 中慢了 85-90%,在 Chromium 18 中慢了约 55%。
回答by Matt
I usually run a check for getContextwhen I create my canvas object.
我通常getContext在创建画布对象时运行检查。
(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.
如果支持,那么您可以继续画布设置并将其添加到 DOM。这是Progressive Enhancement 的一个简单示例,我(个人)更喜欢 Graceful Degradation。
回答by Frozenskys
Why not try modernizr? It's a JS library that provides detection capability.
为什么不试试Modernizr呢?它是一个提供检测功能的 JS 库。
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!
你有没有想过在你的 CSS 中使用 if 语句来获得像 border-radius 这样很酷的特性?好吧,有了 Modernizr,您就可以做到这一点!
回答by Sheikh Ali
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.");
}
回答by kennebec
There may be a gotcha here- some clients do not support allcanvas 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)
回答by Beka
You can use canisuse.jsscript to detect if your browsers supports canvas or not
您可以使用canisuse.js脚本来检测您的浏览器是否支持画布
caniuse.canvas()
回答by Callum Hynes
If you're going to get the context of your canvas, you might as well use it as the test:
如果您要获取画布的上下文,不妨将其用作测试:
var canvas = document.getElementById('canvas');
var context = (canvas.getContext?canvas.getContext('2d'):undefined);
if(!!context){
/*some code goes here, and you can use 'context', it is already defined*/
}else{
/*oof, no canvas support :(*/
}


