Canvas 101 - Getting Started

Let's create a <canvas> element inside our markup, and give it an id of a.

<canvas id="a"></canvas>

Here's is the canvas:

You can see that it's just a blank...canvas at the moment.

But <canvas> is just like other HTML elements, you can specify style, height, id, class etc. You can have more than one <canvas> element on the page and they will maintain independence from each other.

For future canvas, a style="border: 1px solid <color>" attribute will be used to make the canvas boundary easier to see.

Getting the Canvas

We need to use JavaScript to draw on the canvas; so the next step is use JavaScript to get the canvas element. This is the same as with getting any other DOM elements.

var canvas = document.getElementById("a");

Getting the Context

Next we need to get a context on the canvas. The context is an object which provides the methods and properties for actually drawing on the canvas.

Right now the only widely-supported context is the 2d context. Some browsers started on creating a 3d context, but that's been overran by WebGL now.

To get a context, run

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

Now you are ready to draw on it.

Drawing on Context

There are many shapes you can draw on canvas. The simplest one is the rectangle.

A shape has a fill colour, a stroke colour and width, a position and a width and height attributes.

By default the fill colour is black, the stroke colour is ??, the stroke width is 0. And we specify the position, width and height when drawing the shape.

context.fillRect(10, 10, 50, 25);

The fillRect() method takes 4 arguments - x, y, width, height. x and y specifies the coordinate at which the shape should be drawn; the point specifies the top-left of the shape.

Changing colours

We can change the fill colour by changing the fillStyle property on the context. fillStyle can be any valid CSS colour, background or gradient.

After setting fillStyle, all subsequent shapes will use that fill colour.

context.fillStyle = 'green';
context.fillRect(10, 10, 50, 25);
context.fillRect(10, 60, 50, 25);
context.fillStyle = 'red';
context.fillRect(10, 110, 50, 25);