HTML and CSS Reference
In-Depth Information
To get started, here's what you need to know: transformations do not actually affect
your drawing commands or what's currently in the
canvas
element. Instead, transfor-
mations affect the coordinate system, so that all the coordinates that you use in your
subsequent drawing commands are automatically interpreted in the transformed
coordinate system, instead of the original coordinate system.
Say what?! Okay, let's try a different approach. Think of these transformations as
keeping your pen in the same location, but (without the pen touching the paper) moving
the paper underneath your pen to a different location or rotating it at an angle, then
drawing what you planned as if the paper hadn't moved, and then moving the paper
back to its starting position on the desk.
Re-read that last paragraph again, to make sure you understand how coordinate system
transformations affect how you draw into the
canvas
element.
If you translate (or move) the coordinate system 10 pixels to the right and draw a shape
at (0,0) relative to the now-moved coordinate system, the shape actually appears at
(10,0) in the absolute coordinates
relative
to your
canvas
element container.
So, translating the coordinate system 10 pixels to the right and drawing a shape at (0,0)
is basically the same as not translating the coordinate system at all and simply drawing
the shape at (10,0):
mycontext.save();
mycontext.
translate
(10, 0); // move coordinate system 10 pixels right
mycontext.moveTo(0, 0);
mycontext.lineTo(50, 0); // line actually appears from (10,0) to (60,0)
mycontext.stroke();
mycontext.restore();
mycontext.moveTo(10, 0);
mycontext.lineTo(60, 0); // same line, basically
mycontext.stroke();
The same goes for rotation, although the math is a little trickier. If you rotate the canvas
by 30 degrees clockwise and draw a shape at (50,0), it's actually drawn at a relative
location that appears to be 30 degrees down from its horizon:
mycontext.save();
mycontext.
rotate
(Math.PI / 6); // rotate 30 degrees clockwise
mycontext.moveTo(0, 0);
mycontext.lineTo(50, 0); // line actually angles 30 degrees down from horizontal
mycontext.stroke();
mycontext.restore();
At first, you may wonder why translations and rotations are even necessary. After all,
can't you just draw your line or circle at the proper location and in the proper orien-
tation, and not worry about complexity of the transformations?
For some tasks, yes. But again, for more complicated tasks, it's almost imperative that
you transform your coordinate system so that your use of the drawing commands (and,
in particular, which numbers you use for the parameters) is more sensible and semantic.