6.6    Drawing Graphics Using <canvas>

Originally, the term canvas meant work surface. In fact, such an element is initially nothing more than a white area on which you can draw something with the help of JavaScript. Some web developers refer to this element as a programmable img element that you can fill yourself pixel by pixel.

Applications and Games with <canvas>

The canvas element is being used extensively in the web developer community. There are many interesting examples of diagrams or libraries that include single effects up to entire games. The best way to see for yourself is to visit www.effectgames.com/demos/canvascycle/ to see what is already made possible by <canvas>.

In the introductory <canvas> tag, you must use the HTML attribute id to specify a document-wide unique name, width to specify the width of the canvas, and height to specify the height of the canvas. The use of a unique id is especially important for accessing the canvas element with JavaScript. It’s also possible to use multiple canvas elements in one HTML document.

For this purpose, here’s a simple example in which an empty canvas drawing area with 400 × 200 pixels is displayed. For you to see this drawing area in the example, I’ve also defined a simple frame around the canvas element:

...
<h1>Creating a drawing area with canvas</h1>
<canvas id="myCanvas" width="400" height="200">
Your browser does not support the canvas element.
</canvas>
...

Listing 6.11     /examples/chapter006/6_6/index.html

With <canvas>, you initially provide merely an empty drawing area in the HTML document. In this example, I’ve additionally inserted an alternative text between <canvas> and </canvas>, which is only displayed if the web browser doesn’t support <canvas> or the user has JavaScript disabled. Another option is to use a pixel graphic instead of text, if that makes sense.

Canvas Application Programming Interface

As mentioned at the beginning, the canvas element enables you to provide only the drawing area in the HTML document. By means of JavaScript and a corresponding interface (Canvas API), you can fill this area. Here, I’ve only dealt with the HTML element <canvas> as an introduction.