HTML5 Canvas element

17 November, 2015ipivanovNo CommentsJavaScript
54

The HTML 5 canvas specification has introduced a slew of new and exciting technologies to the web. Here we’ll expand on just one: the Canvas API. It’s for drawing pretty, whizzy things.Canvas is a new DOM API for drawing on a 2- or 3-dimensional (you guessed it) canvas. What follows just looks at the 2D version, but the 3D technology is called WebGL and there are some incredible things being done with it.

The first thing to know is that canvas is a new element in the HTML 5 specification. To begin drawing on the canvas, you grab hold of it and retrieve a particular context – either 2d or webgl:

The getContext function retrieved the correct context, which is an object whose methods are used to draw, fill and generally modify the canvas. Above we’re using fillRect, which takes the x and y position of the top left corner of the rectangle as the first two arguments, and the width and height dimensions as the latter two.

Animation

canvas works a bit like a real canvas – pixels are drawn and layered on top of each other until you erase – clear – them. This means that if you want to animate something moving across a canvas you have to repeatedly clear the canvas (or a section of it) and redraw the scene.

In the next example we’ve animating the square bouncing around the canvas, which automatically resizes to fill the screen. loop is the business part of the code. TheclearRect function is used to clear the entire canvas before each frame.