HTML and CSS Reference
In-Depth Information
Because this chapter serves as an overview for you to get the foundation to work through the rest of the
book, we won't go into the details for each method. For a more exhaustive treatment of the canvas
drawing API, see the specification at http://developers.whatwg.org/the-canvas-element.html , or
read one of the more detailed guides listed at the beginning of this topic.
The canvas context
Every canvas element contains a drawing context , an object that exposes the drawing API. To access the
context, use the following code:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
The first line uses the DOM interface to find our canvas element with an id of 'canvas' . Call this object's
method getContext with the string argument '2d' , which specifies the type of drawing API to use.
It's worth mentioning, this is the only standardized drawing context at the time of this writing. Although
some vendors have experimented with a 3D API, this has not been implemented across browsers and is
not part of the HTML5 specification.
Now that we have our canvas element and access to its context, we can start drawing with it!
Removing the drawing with clearRect
In most animations, we must clear the canvas every frame before drawing something else, which is how
we simulate motion. By drawing something, erasing it, and drawing it someplace else, we can make a
series of images look like a single object that has moved, rather than two frames displayed sequentially.
The method context.clearRect(x, y, width, height) clears the specified rectangle by erasing
every pixel inside it, setting them to transparent black. As such, any previously drawn graphics, such as
lines or fills, will no longer be visible. Because we use this method to clear entire animation frames, you
will see it called in the examples like this:
context.clearRect(0, 0, canvas.width, canvas.height);
This creates a rectangle the size of the entire canvas element and positions it at the canvas origin, clearing
everything that was previously drawn.
This is a complete canvas clear, but there are a few optimizations to consider. If you know that an
animation will only affect a portion of the frame, you can specify a smaller rectangle in clearRect to save
some processing. It's also possible to stack multiple canvas elements on top of each other. Because
they're transparent, you see the composite image. This can be useful if you have a background image that
you do not want to draw every frame. You can just place it as a background canvas or image element and
animate over top of it.
 
Search WWH ::




Custom Search