Home and Learn: Web Design Course

The HTML 5 Canvas Tag

One tag new to HTML5 is the Canvas tag. The Canvas tag is a blank space on which you can draw anything you like. You can add images to a Canvas, animate your shapes, add text, and a whole lot more besides.

To get the most out of the Canvas tag, however, you need to be able to code using Javascript. Another disadvantage is that not all browsers support the Canvas tag, especially versions of Internet Explorer below version 9. You can, however, write some quite sophisticated browser apps and games using just the Canvas tag and Javascript, and all without plug-ins like Adobe's Flash.

To draw a Canvas, all you need is these two tags in the BODY of your HTML pages:

To draw a Canvas, all you need is these two tags in the BODY of your HTML pages:



You can specify a height and width for your canvas:



If you don't specify a height and width, the canvas will be 300 pixels in width and 150 pixels in height.

The canvas is entirely transparent. If you want it to have, say, a border, you can use some CSS:



border: 1px solid #000000;



To do something useful with your canvas, you need to give it an ID. Once it has an ID, you can get a reference to it with Javascript.

<CANVAS HEIGHT="400" WIDTH="400" ID="MyCanvas">


In the code below, we use "MyCanvas" to place the canvas ID into a variable (memory storage area):


var canvasID = document.getElementById("MyCanvas");


You then to specify how you're going to be using your canvas, 2D or 3D:

var canvas = canvas.getContext("2d");

Once you have a reference to your canvas, and a context, you're ready to begin drawing on it. Obviously, this is a complex subject, and a whole book in itself. If you want to explore further, try this page on Mozilla's site:


In the next part, we'll take a look at a few more HTML 5 tags.

Back to the Home Page


Email us: enquiry at homeandlearn.co.uk