HTML and CSS Reference
In-Depth Information
The
translate
method can help me here. It moves the 0, 0 coor-
dinate to a new position.
Figure 5.13
shows that I've drawn a dot
and also shows the arguments I passed to translate. Each time
translate
runs it sets the new coordinates to 0, 0. Note that
the translate doesn't rotate or move the canvas in a way that's
presented to the user; it's translating the underlying coordinate
system that subsequent drawing functions refer to.
FIguRE 5.13
Example of how
translate
can move the
origin points of the canvas.
Now to achieve my rotating spiral I need to initialise the can-
vas using
translate
, and then use
setInterval
to redraw my
spiral (note that
drawSpiral
is my own function, rather than a
native method, that draws the path for a spiral with a series of
stroke
calls):
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
drawSpiral(); // the complicated magic mathematics
setInterval(function () {
ctx.clearRect(-ctx.canvas.width/2, -ctx.canvas.height/2,
ctx.canvas.width, ctx.canvas.height);
ctx.rotate(Math.PI / 180 * 0.5) // 1/2 a degree
drawSpiral();
}, 10);
The only caveat I have to deal with is clearing the canvas. I
would normally use
clearRect(0, 0, width, height)
, but since
translate
has moved the 0, 0 position to the centre of the can-
vas, I need to manually specify the top left, as seen in the previ-
ous code listing.