Chapter 9. <canvas>

Kyle Simpson

Introduction

One of the most exciting additions to web pages to be standardized by HTML5 is the canvas element:

<canvas id="mycanvas"></canvas>

This simple element allows users to draw graphics such as lines, circles, and fills directly into a rectangle-shaped block element that appears on the web page.

There are numerous features associated with the canvas element. For example, in addition to drawing images manually, browsers can take raw image data from an external image file and “draw” it onto the canvas element.

You can also erase and redraw all or a portion of the canvas image. The ability to edit canvas images lends itself to the creation of animations, where you appear to move elements around by drawing and redrawing them in varying positions.

In addition, canvas elements can have transparency, which means they can be layered or stacked on top of each other to create more sophisticated graphical images/effects. There are also a number of transformations and effects that you can apply to your canvas drawings. In essence, a canvas image is a dynamic image, unlike a static PNG or JPEG file.

In much the same way that you might draw an image using a graphics program like Adobe Photoshop, save it to a file, and load it into a web page, with canvas you can automate the drawing commands through code and immediately see the results on the page, without the need for loading an external file.

This capability allows you to do many sophisticated things that were ...

Get HTML5 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.