HTML5 Canvas: test whether the browser supports the Canvas method. html5canvas
This article mainly introduces how to test whether the browser supports Canvas in HTML5 Canvas. This article provides two native methods and a modernizr class library. For more information, see
This article is translated from Steve Fulton & Jeff Fulton HTML5 Canvas, Chapter 1, "Testing to See Whether the Browser Supports Canvas ".
After obtaining the reference of the Canvas element on the HTML page, we need to test whether the element contains the context ). Canvas context refers to the plane defined by the browser for painting. To put it simply, if the context does not exist, the Canvas name will be saved. There are several ways to test whether the browser supports Canvas. The first method is to check whether the getContext method of the Canvas Element in the HTML page exists:
The Code is as follows:
If (! TheCanvas |! TheCanvas. getContext ){
Return;
}
In fact, the above Code tests two points: first, it tests whether theCanvas is false (if the id does not exist, document. getElementById () returns false); second, tests whether the getContext () function exists.
In the above Code, if the test fails, the return Statement is executed and the program is terminated.
Another method is to create a function specifically used to determine whether a Canvas is supported. In this function, a Canvas element is generated in real time for such determination. This method is very popular, mark Pilgrim mentioned this solution in his HTML5 website http://diveintohtml5.org:
The Code is as follows:
Function canvasSupport (){
Return !! Document. createElement ('canvas '). getContext;
}
Function canvasApp (){
If (! CanvasSupport ()){
Return;
}
}
Our favorite approach is to use the modernizr. js Library (which can be found in http://www.modernizr.com ). Modernizr is an easy-to-use lightweight JavaScript library used to test the compatibility of various Web technologies-it provides many static Boolean methods that can be used to test whether the current Canvas is supported.
Introducing modernizr on the HTML page is simple, download the code from the http://www.modernizr.com, and then include this external js file in the HTML page:
The Code is as follows:
<Script src = "modernizr-1.6.min.js"> </script>
To use Modernizr to test Canvas support, you only need to change the canvasSupport function above:
The Code is as follows:
Function canvasSupport (){
Return Modernizr. canvas;
}
We believe that using Modernizr. js is the best solution to determine whether the browser supports Canvas.