HTML and CSS Reference
In-Depth Information
Testing to See Whether the Browser Supports Canvas
Now that we have a reference to the canvas element on the HTML page, we need to
test to see whether it contains a context . The Canvas context refers to the drawing
surface defined by a web browser to support Canvas. Simply put, if the context does
not exist, neither does the canvas. There are several ways to test this. This first test
looks to see whether the getContext method exists before we call it using Canvas, as
we have already defined it in the HTML page:
if (!theCanvas || !theCanvas.getContext) {
Actually, this tests two things. First, it tests to see whether theCanvas does not contain
false (the value returned by document.getElementById() if the named id does not exist).
Then, it tests whether the getContext() function exists.
The return statement breaks out and stops execution if the test fails.
Another method—popularized by Mark Pilgrim on his HTML5 website, http://divein —uses a function with a test of a dummy canvas created for the sole purpose
of seeing whether browser support exists:
function canvasSupport () {
return !!document.createElement('testcanvas').getContext;
function canvasApp() {
if (!canvasSupport) {
Our favorite method is to use the modernizr.js library, which you can find here: http:// . Modernizr—an easy-to-use, lightweight library for testing sup-
port for various web-based technologies—creates a set of static Booleans that you can
test against to see whether Canvas is supported.
To include modernizr.js in your HTML page, download the code from http://www.mod and then include the external .js file in your HTML page:
<script src="modernizr-1.6.min.js"></script>
To test for Canvas, change the canvasSupport() function to look like this:
function canvasSupport () {
return Modernizr.canvas;
We are going to use the modernizr.js method because we think it offers the best ap-
proach for testing whether Canvas is supported in web browsers.
Search WWH ::

Custom Search