Home > Web Front-end > H5 Tutorial > HTML5 Canvas: How to test whether the browser supports Canvas_html5 tutorial skills

HTML5 Canvas: How to test whether the browser supports Canvas_html5 tutorial skills

WBOY
Release: 2016-05-16 15:47:02
Original
1722 people have browsed it

This article is translated from Steve Fulton & Jeff Fulton HTML5 Canvas, Chapter 1, “Testing to See Whether the Browser Supports Canvas”.

After getting the reference to the Canvas element on the HTML page, we need to test whether the element contains "context". The context of a Canvas refers to the plane defined by the browser for drawing. Simply put, if the context does not exist, Canvas exists in name only. There are several ways to test whether a browser supports Canvas. The first method is to check whether the getContext method of the Canvas element in the HTML page exists:

Copy the code
The code is as follows:

if (!theCanvas || !theCanvas.getContext) {
return;
}

In fact, the above code tests two points: one , tested whether theCanvas is false (if the id does not exist, document.getElementById() will return false); secondly, tested whether the getContext() function exists.

In the above code, if the test fails, then the return statement is executed and the program terminates.

Another method is to create a function specifically used to determine whether Canvas is supported, and in this function, a Canvas element is generated in real time to make this determination - this method is very popular, Mark Pilgrim in his HTML5 This solution is mentioned on the website http://diveintohtml5.org:

Copy the code
The code is as follows:

function canvasSupport() {
return !!document.createElement('canvas').getContext;
}
function canvasApp() {
if (!canvasSupport()) {
return;
}
}

Our favorite method is to use the modernizr.js library (found at http://www.modernizr.com). Modernizr is a simple and easy-to-use lightweight JavaScript library for testing 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 into the HTML page is very simple, download the code from http://www.modernizr.com, and then include this external js file in the HTML page:

Copy the code
The code is as follows:

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template