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) {
   return;
}

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—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('canvas').getContext;
}
function canvasApp() {
   if (!canvasSupport) {
      return;
  }

}

Our favorite method is to use the modernizr.js library. Modernizr—an easy-to-use, lightweight library for testing support 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 ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.