Canvas & SVG: Handling Non-supporting Browsers - JUMP START HTML5 (2014)

JUMP START HTML5 (2014)

Chapter 14 Canvas & SVG: Handling Non-supporting Browsers

In this short chapter, we'll look at creating code that tells the browser how to behave if it doesn't support canvas rendering.

Create Alternative Content

The best way to handle the possibility that a user's browser doesn't support canvas is to place alternative content within the <canvas> tag. This does away with confusion for the end user if they can't see what's supposed to be displayed.

You can use an img tag, explanatory text, or any other HTML you think necessary for this alternative content. For example:

<canvas id="MyCanvas" width="150" height="300">

<img src="http://yoursite.com/locationofimage.jpg"

↵alt="Browser Not Supported" />

</canvas>

If the browser supports canvas, the img tag and any other content between the <canvas> and </canvas> tags are ignored and won't appear in the document.

How useful you want to make fallback content is up to you; you can offer a download link to the latest version of the user's browser, or you can add a framework that'll allow you to show the content using a different technology, such as SVG or Flash.

You can also use the getContext method to check for canvas support in JavaScript, e.g.

function supports_canvas() {

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

}

Alternatively, you can use the getContext method on an existing element:

var canvas = document.createElement("MyCanvas");

if (!canvas.getContext || !canvas.getContext("2d")) {

alert("Sorry - canvas is not supported.");

}

else {

// start drawing

var ctx = canvas.getContext('2d');

}