An introduction to HTML5 canvas: part 1
THE <canvas> tag which was introduced in the HTML5 spec acts as a container for graphics to be drawn in. The canvas element itself is useless without the 2D drawing API and that’s what I’ll be look at here.
Firstly, I’d like to point out that elements drawn in the canvas are not part of the DOM and therefore cannot be bound to events. If you want your elements to respond to events, I would suggest using SVG instead.
Ok so we have that out of the way.
I’ll be using some examples to help illustrate how canvas works during this article.
<canvas id="myCanvas" width="400px" height="400px"></canvas>
The first thing to understand about canvas is that you don’t actually draw on the canvas element itself, but rather a canvas “context” which the javascript API provides. The context is basically a drawing stack that holds all of our drawings. So let’s go ahead and define the context.
var canvas2D = document.getElementsById('myCanvas').getContext('2d')
At the moment we’re limited to a 2D context. From now on, when we want to interact with the contents of the canvas, we’re going to be calling methods on ‘canvas2D’, a full list of which can be seen here.
So let’s get started by drawing a rectangle. To do so we’re going to use the fillRect method which is defined in the spec …





