Cross-Browser HTML5 Canvas with Fallback

Share this article

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.

Frequently Asked Questions about HTML5 Canvas

What is the purpose of the getContext() method in HTML5 Canvas?

The getContext() method is a critical part of working with HTML5 Canvas. It returns a drawing context on the canvas, or null if the context identifier is not supported. The context is what you use to draw on the canvas. The two most common types of contexts are ‘2d’ for two-dimensional graphics and ‘webgl’ for three-dimensional graphics. The ‘2d’ context allows for shapes, text, and images to be drawn on the canvas, while ‘webgl’ context provides a 3D rendering context.

How can I create a fallback content for HTML5 Canvas?

Fallback content is essential for browsers that do not support HTML5 Canvas. To create fallback content, you simply place the alternative content inside the canvas element. If the browser does not support canvas, it will display the fallback content. If it does support canvas, it will ignore the fallback content and render the canvas as expected.

How can I draw shapes using HTML5 Canvas?

Drawing shapes with HTML5 Canvas involves using a series of methods available through the ‘2d’ context. For instance, to draw a rectangle, you can use the fillRect(x, y, width, height) method, where x and y specify the position on the canvas (relative to the upper left corner) and width and height are the rectangle’s size.

How can I add text to a canvas?

To add text to a canvas, you can use the fillText(text, x, y) method. The text parameter is the text you want to display, while x and y set the position of the text on the canvas. You can also use the strokeText(text, x, y) method to create outlined text.

How can I draw images on a canvas?

To draw an image on a canvas, you can use the drawImage(image, x, y) method. The image parameter is the image that you want to draw, and x and y set the position of the image on the canvas.

How can I clear a canvas?

To clear a canvas, you can use the clearRect(x, y, width, height) method. This method clears the specified rectangle area, making it fully transparent.

How can I save the current state of a canvas?

To save the current state of a canvas, you can use the save() method. This method saves the current styles and transformations, and you can then restore these states later using the restore() method.

How can I apply transformations to a canvas?

Transformations in a canvas can be applied using various methods like rotate(angle), scale(x, y), and translate(x, y). The rotate method rotates the canvas clockwise by a specified angle, scale scales the canvas by the x and y factors, and translate moves the canvas and its origin to a different point.

How can I create a gradient effect on a canvas?

To create a gradient effect, you can use the createLinearGradient(x1, y1, x2, y2) or createRadialGradient(x1, y1, r1, x2, y2, r2) methods. These methods create a linear or radial/circular gradient that can be used to fill or stroke shapes.

How can I draw a path on a canvas?

To draw a path, you can use the beginPath(), moveTo(x, y), lineTo(x, y), and closePath() methods. The beginPath method starts a new path, moveTo sets the starting point of the path, lineTo adds a new point and creates a line from that point to the last specified point in the canvas, and closePath creates a path from the current point back to the starting point.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

canvasHTML5 Dev CenterHTML5 Tutorials & Articles
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week