How to determine if browser support HTML canvas element

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

To determine if the user’s browser support the <canvas> HTML element, we use feature testing.

For example, suppose we have HTML code with the canvas element …

<canvas id="mycanvas">
Sorry, your browser does not support canvas

Browsers that support the canvas element will not display the content within the canvas tags.  Those browsers that do not support the canvas element will display the content within the tags.

Then we can write some Javascript to get the context of the canvas and see if the context exist…

var theCanvas = document.getElementById("mycanvas");
var theContext = theCanvas.getContext("2d");
if ( theContext ) {
    // browser supports canvas, use theContext here
} else {
   // browser does not support canvas

The code says that if context exist, then browser supports canvas.  Otherwise, it does not.

Another way to detect support for canvas is the following Javascript …

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

The javascript creates an canvas element and attempts to get it context.  If gotten, it returns true indicating canvas support.  If return is false, browser does not support canvas.  The double exclamation marks just converts the expression to a boolean type.  It does not negate nor change the sign of the boolean.

Browsers that don’t support canvas (such as Internet Explorer 7 and 8), you can use ExplorerCanvas polyfill to enable them to support canvas.