HTML and CSS Reference
In-Depth Information
Solution
The canvas API provides several commands for transforming your canvas drawing
actions:
translate( x , y )
Move/skew the location of the origin point for the coordinate system from (0,0) to
( x , y ).
scale( x , y )
Scale the units of the coordinate system in the x and y directions, independently.
rotate( angle )
Rotate the coordinate system about the origin point, (0,0), by the angle (moving
in a clockwise direction) specified in radians.
When you start combining multiple transformations, it is often easier to manage the
state of the canvas element on a stack, where you can simply revert back one level to
undo all transformations (and other state, like style/color settings) with one command.
The canvas API provides two commands for managing your state stack, save() and
restore() :
mycontext. save (); // save the current state of the canvas
mycontext.translate(10, 10); // move the origin point to (10,10)
mycontext.arc(0, 0, 10, 0, Math.PI * 2, true); // draw a circle
mycontext.stroke();
mycontext. restore ();
mycontext. save ();
mycontext.rotate(Math.PI / 4); // rotate 45 degrees clockwise
mycontext.moveTo(0, 0);
mycontext.lineTo(10, 0);
mycontext.stroke();
mycontext. restore ();
In both these transformations, the action taken could easily be reversed. That is, we
could easily translate back to our original origin point with translate(−10, −10) , or
back to our original rotation with rotate(Math.PI / −2) .
However, as soon as you start combining multiple translations at once, or nesting
translations into multiple steps or layers, stack management becomes quite necessary.
It is best practice to always use stack management for your canvas element's state as
you make style changes or transformations.
Discussion
The concept of using transformations to adjust your drawing commands is probably
going to be a bit strange to you at first. Most developers are initially a little confused
by this idea. Don't worry, though; after you've done it a few times you'll get more
comfortable with this new mindset, and it won't seem quite so foreign.
 
Search WWH ::




Custom Search