A 3D Exploration of the HTML Canvas Element : Page 2

The HTML Canvas, an element of the upcoming HTML 5 specification, allows you to efficiently draw arbitrary graphics at the primitive or individual pixel level. Find out how to implement a 3D rendering using the HTML Canvas.

by Greg Travis

Aug 26, 2008

Page 2 of 4

The Basics of the HTML Canvas
To understand the HC better, consider the basic model it uses. The rendering of a graphics primitive is affected by many parameters. If all of these were parameters to a function, it might look like this:

As you can imagine, this style gets cumbersome. That's why many graphics APIs use something called a state machine. In the state machine model, settings such as dotted_style, anti_alias, end_cap_style, and so on, are settings of the graphics context rather than parameters to a primitive function.

This way, you can set the parameters you need, and ignore the ones you don't. You can also use group settings for multiple primitives, as follows:

Save and Restore
One of the advantages of the HC's state machine model is also a disadvantage. After you set a parameter like fillStyle, that setting will affect all primitives drawn thereafter. This saves a lot of typing, but it can also cause a lot of headaches if the settings of one part of the code affect another part of the code.

The solution for this blessing/curse dilemma consists of a pair of methods: save() and restore(). The save() method will store the current graphics settings, and the restore() method will bring those settings back. Any changes you make to the settings in-between will disappear after restore() is called.

The function wacky() makes a bunch of wacky changes to the graphics context, presumably to render something wacky-looking. But the changes are sandwiched between calls to save() and restore(), so when wacky() returns, all the changes are gone. That's why wacky() can be called from normal() in between two calls to strokeRect() without your having to worry that the two rectangles will look different.

Note also that you can nest calls to save() and restore(), because they actually store graphics contexts on a stack:

context.save();
// change state
// draw draw draw
context.save();
// change state even more
// draw draw draw
context.restore();
// change state back to the first set of changes
// draw draw draw
context.restore();

The first and third batches of drawing commands operate under the same context.

The Graphics Context
You don't draw directly to the HC. Rather, you acquire a 2D graphics context from the canvas and draw to that: