HTML and CSS Reference
Yo u ' v e a l r e a d y s e e n s o m e b a s i c a n i m a t i o n s u s i n g c a n v a s
throughout this chapter, but I wanted to explain some of the
concepts in detail here.
Animation is very basic and manual on a canvas. If there's an
area that you want to animate, you must draw, clear the area,
draw again, and rinse and repeat.
As you'll fi nd out, it's a blast to navigate around the canvas with a pen
drawing lines and fi lling shapes, but there are already some librar-
ies available that make working with the canvas much easier. One of
written by the author of jQuery, John Resig.
It's not actually a library designed to ease working with canvas, but
turn drawn on the canvas element. In many ways, processing.js is a
great tool for visualisation and abstracts away a lot of the more compli-
cated drawing and animation procedures in the 2D drawing API.
Simple animation is mostly about clearing the current canvas
state and drawing the whole thing again. As the canvas is a
native drawing API, it's very quick to do so. I'll show you a demo
that takes Bruce's bouncy head and bounces it around the can-
vas area. This example is based on the canvas breakout tutorial
by Bill Mill, but I jazzed it up with Bruce's mug bouncing instead
of a solid black ball.
The code used for Figure 5.18 is relatively simple and breaks
down into the following tasks:
1. initialise the canvas and objects I want to draw
2. clear the canvas
3. draw the ball on the canvas
To a d d e x t r a s p i c e , I r To t a t e B r u c e 's f a c e i in c i r c l e s w h i l s t h e b To u in c e s
around. So I'll have to do some rotation on the canvas, too.