Canvas

HTML5 defines the <canvas> element as “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.” A canvas is a rectangle in your page within which you can use JavaScript to draw anything you want. HTML5 defines a set of functions (“the canvas API”) for drawing shapes, defining paths, creating gradients, and applying transformations.

Checking for canvas API support uses detection technique #2 (see Detection Techniques). If your browser supports the canvas API, the DOM object it creates to represent a <canvas> element will have a getContext() method (see Simple Shapes). If your browser doesn’t support the canvas API, the DOM object it creates for a <canvas> element will have only the set of common properties, not anything canvas-specific. You can check for canvas support using this function:

function supports_canvas() {
  return !!document.createElement('canvas').getContext;
}

This function starts by creating a dummy <canvas> element:

return !!document.createElement('canvas').getContext;

This element is never attached to your page, so no one will ever see it. It’s just floating in memory, going nowhere and doing nothing, like a canoe on a lazy river.

As soon as you create the dummy <canvas> element, you test for the presence of a getContext() method. This method will only exist if your browser supports the canvas API:

return !!document.createElement('canvas').getContext;

Finally, you use the double-negative ...

Get HTML5: Up and Running 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.