HTML and CSS Reference
In-Depth Information
How would you draw a rectangle at an angle? Well, you could calculate the vertices
using geometric calculations and then manually draw the four sides as individual lines.
But who wants to do it that way? Instead, rotate the coordinate system and call the
rect(...) command; it's as simple as that.
Scaling is another example of something that almost always requires transformations
to work properly, specifically because scaling can be done independently in both the
x and y directions. What scaling amounts to is saying that if you scale the x direction
of your coordinate system to twice as large, and you draw a line that is supposed to be
50 units (pixels) long, it actually is rendered as twice as long (100 pixels):
mycontext.save();
mycontext. scale (2, 1); // scale x direction units by a factor of 2
mycontext.moveTo(0, 0);
mycontext.lineTo(50, 0); // line actually appears to extend to (100,0)
mycontext.stroke();
mycontext.restore();
mycontext.moveTo(0, 0);
mycontext.lineTo(100, 0); // same line, basically
mycontext.stroke();
Other tasks—rotating an image, for instance—also beg for transformations, because
it would be very difficult (and certainly, performance-wise, impractical) to manually
transform the raw bitmap image data array yourself. Instead, you simply rotate the
coordinate system and draw the image into it, and the canvas element does the hard
work for you:
mycontext.save();
mycontext. rotate (Math.Pi / 4); // rotate 45 degrees clockwise
mycontext. drawImage (img, 0, 0); // draw the image at (0,0)
// in the rotated coordinate system
mycontext.restore();
Finally, let's take a look at nesting transformations, to reinforce why transformations
and stack management of the canvas element's state are helpful (as shown in
Figure 9-12 ):
mycontext.beginPath();
mycontext.strokeStyle = "#f00"; // red color
mycontext.translate(20, 20); // move the coordinate system to (20,20) origin
mycontext.moveTo(0, 0); // actually (20,20)
mycontext.lineTo(80, 10); // actually (100,30)
mycontext.stroke();
mycontext. save (); // save <canvas> state
mycontext.beginPath();
mycontext.strokeStyle = "#00f"; // now blue color
mycontext.rotate(Math.PI / 4);
mycontext.moveTo(0, 0);
mycontext.arc(0, 0, 52, Math.PI / 3, Math.PI / 6, true);
mycontext.closePath(); // connects back to the start of the path
 
Search WWH ::




Custom Search