HTML5 – Canvas Element

The HTML <canvas> element is a new element added in HTML5. It is used to draw graphics, on the fly, usually with Javascript. The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics. The markup is simple:

<canvas id="canvas" width="800" height="400"></canvas>

As you can see it’s very similar to an <img> element without the src and alt attributes. You must always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas.

Since the <canvas> element isn’t supported in older browsers you should alway supply fallback content. To do so simply provide the image content within the <canvas> like so:

<canvas id="canvas" width="150" height="150">
  <img src="{You Image Path}" width="150" height="150" alt=""/>

The 2d rendering context is used to draw on the context. The <canvas> element exposes different rendering context: 2d and 3d. The 3d rendering context is based on OpenGL ES and is still in the experimental phase so we’ll focus on the 2d rendering context. The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions .getContext() takes one parameter, the type of context.

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

All we’re doing here is assigning the canvas element to a variable then assigning the 2d rendering context to another variable by calling the getContext method. Now we have a variable that contains the 2d rendering context we can begin to draw stuff. Adding the following code will render a black square:

ctx.fillRect(40, 40, 100, 100);

Demo Time!
The <canvas> element can also be used to render animations. The script below creates a looping panoramic image scroller. The script is commented so you can get a basic understanding of what it’s doing. To view the demo, click the following link:

    <script type="text/javascript">
		var img = new Image();
		//User Variables
		img.src = '/Media/StateOfDotNET.JPG';
		var CanvasXSize = 800; //width of canvas element
		var CanvasYSize = 400; //height of canvas element
		var speed = 30; //lower is faster
		var scale = 1.05;
		var y = -4.5; //vertical offset
		var dx = 0.75;
		var imgW; //image width
		var imgH; //image height
		var x = 0;
		var clearX;
		var clearY;
		var ctx; //canvas element
		img.onload = function() {
    		imgW = img.width*scale;
    		imgH = img.height*scale;
    		if (imgW > CanvasXSize) { x = CanvasXSize-imgW; } // image larger than canvas
    		if (imgW > CanvasXSize) { clearX = imgW; } // image larger than canvas
    		else { clearX = CanvasXSize; }
    		if (imgH > CanvasYSize) { clearY = imgH; } // image larger than canvas
    		else { clearY = CanvasYSize; }
    		//Get Canvas Element
    		ctx = document.getElementById('canvas').getContext('2d');
    		//Set Refresh Rate
    		return setInterval(draw, speed);
		function draw() {
    		//Clear Canvas
    		//If image is <= Canvas Size
    		if (imgW <= CanvasXSize) {
       	 	//reset, start from beginning
        		if (x > (CanvasXSize)) { x = 0; }
        		//draw aditional image
        		if (x > (CanvasXSize-imgW)) { ctx.drawImage(img,x-CanvasXSize+1,y,imgW,imgH); }
    		//If image is > Canvas Size
    		else {
        		//reset, start from beginning
        		if (x > (CanvasXSize)) { x = CanvasXSize-imgW; }
        		//draw aditional image
        		if (x > (CanvasXSize-imgW)) { ctx.drawImage(img,x-imgW+1,y,imgW,imgH); }
    		//draw image
    		//amount to move
    		x += dx;

The Source Code for the demo page is available on GitHub.

Note: The <canvas> element is supported in Firefox 1.5 and later, Opera 9 and later, newer versions of Safari, Chrome, and Internet Explorer 9.

One thought on “HTML5 – Canvas Element

Leave a Reply

Your email address will not be published. Required fields are marked *

Please Do the Math