Cross-Browser HTML5 Canvas with Fallback

Tweet

Canvas is a relatively new HTML5 technology that provides a “scriptable” image. You can add a <canvas> element to your page and draw on its surface using JavaScript commands. It’s very fast and could be used for action games and animated charts — see “3 Great JavaScript & Canvas Examples.”

A canvas tag can be placed on an HTML5 page with the following code:


<canvas id="mycanvas" width="300" height="300">
Sorry, your browser cannot display this image.
</canvas>

Assuming canvas is supported, JavaScript can be used to draw directly onto the canvas; for example, a black circle with 100px radius in the center of the image:


var canvas = document.getElementById("mycanvas");
var cxt = canvas.getContext("2d");
cxt.arc(150,150,100,0,Math.PI*2,true);
cxt.fill();

That’s great, but it’s hardly a pleasant experience for people using a browser without <canvas> support.

There are several projects that implement canvas support in Internet Explorer 8.0 and below, but they cannot fix other browsers. We can fall back to text (as shown) or an img, but that requires extra markup, and it won’t appear if the browser supports canvas but has JavaScript disabled. In that situation, the user sees an empty box.

In order to keep everyone happy, we’ll build a page that shows a simple canvas raindrop animation. If you’re in the UK, it’ll remind you of a glorious British summer. A static image will appear when the user’s browser is without <canvas> or JavaScript support.

Working through the code, our HTML5 head contains a small script that declares a canvas element. This adds nothing to the page; it’s a workaround for IE8 and below that allows us to apply CSS styles to a canvas tag, even though the browser is not HTML5-aware (alternatively, we could have used the HTML5 JavaScript shiv):


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Canvas Example</title>
<script>
document.createElement("canvas");
</script>

We can now define CSS styles for our canvas tag. When the page loads, the element is given a background image (rain.jpg) that everyone can see. The #mycanvas.active declaration removes this background, but it will only activate once our script runs successfully:


<style>
#mycanvas
{
	float: left;
	width: 300px;
	height: 300px;
	margin: 0 20px 0 0;
	background-image: url(rain.jpg);
	border: 1px solid #000;
}

#mycanvas.active
{
	background-image: none;
}
</style>

We can now place a canvas tag on the page. There’s no need to provide fallback text, as users will see the static background image when it’s unsupported:


</head>
<body>

<h1>HTML Canvas Example with Image Fall Back</h1>

<canvas id="mycanvas" width="300" height="300"></canvas>

We’re now ready to add some JavaScript magic — assuming the user has scripting enabled. The first few lines check whether canvas is supported, and applies a class of “active” to the element to remove the static background:


<script>
var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {

	// canvas supported
	canvas.className = "active";

Our raindrop animation code can now execute:


	// start animation
	var cxt = canvas.getContext("2d");
	cxt.fillStyle = "rgba(255,255,255,0.5)";

	setInterval(function() {
		var	x = Math.round(Math.random()*canvas.width),
			y = Math.round(Math.random()*canvas.height),
			e = 20 + Math.round(Math.random()*30),
			s = 0;

		(function() {
			s++;
			if (s <= e) {
				setTimeout(arguments.callee,s);
				var c = 255-(e-s)*3;
				cxt.strokeStyle = "rgb("+c+","+c+","+c+")";
				cxt.beginPath();
				cxt.arc(x,y,s,0,Math.PI*2,true);
				cxt.fill();
				cxt.stroke();
			}
		})();
	},100);

}
</script>

</body>
</html>

This is a simple demonstration, but it illustrates how you can use new HTML5 technologies while retaining a level of support for older browsers. The same concept could be used in other applications; for example, you could provide an animated chart that falls back to a static, server-generated image when canvas or JavaScript is unavailable.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments