HTML5 defines the <canvas>
element as “a resolution-dependent bitmap canvas which can be used
for rendering graphs, game graphics, or other visual images on the fly.” A
canvas is a rectangle on your page in which you can use JavaScript to draw
anything you want. The following table shows which browsers offer basic
canvas support at the time of this writing:
IE[a] | Firefox | Safari | Chrome | Opera | iPhone | Android |
---|---|---|---|---|---|---|
7.0+ | 3.0+ | 3.0+ | 3.0+ | 10.0+ | 1.0+ | 1.0+ |
[a] Internet Explorer support requires the third-party explorercanvas library. |
So what does a canvas look like? Nothing, really. A <canvas>
element has no content and no
border of its own. The markup looks like this:
<canvas width="300" height="225"></canvas>
Figure 4-1 shows the canvas with a dotted border so we can see what we’re dealing with.
You can have several <canvas>
elements on the same page. Each
canvas will show up in the DOM, and each canvas maintains
its own state. If you give each canvas an id
attribute, you can access them just like you
would any other element.
Let’s expand that markup to include an id
attribute:
<canvas id="a" width="300" height="225"></canvas>
Now we can easily find that <canvas>
element in the
DOM:
var a_canvas = document.getElementById("a");