HTML and CSS Reference

In-Depth Information

So now when you move to 10, 20, since this is relative to the new origin, the actual position (relative to the

canvas), will be 110, 70. You might be wondering why you would want to do this. Well, suppose you were drawing

a picture of the United States flag, which has 50 stars on it. A five-pointed star is a fairly complex shape to draw,

which will require a number of drawing commands. Once you have drawn the first star, you'll need to repeat the

process 49 more times, with each time using different values.

By simply translating the context to the right a little, you can repeat the exact same commands using the

same values. But now the star will be in a different location. Granted, you could accomplish the same thing by

creating a
drawStar()
function that accepted
x
,
y
parameters. Then call this 50 times passing in different values.

However, once you get used to using transformation you will find this easier, especially with the other types such

as rotation.

The rotate transformation doesn't move the origin; instead it rotates the x and y axis by the specified

amount. A positive amount is used for a clockwise rotation and a negative value is used to rotate counter-

clockwise. Figure
10-7
demonstrates how a rotate transformation works.

Rotate -30°

0, 0

Figure 10-7.
Rotating the drawing context's grid

■
I indicated the rotation angle as 30° since that is what most people are familiar with. However, the

rotate()
command expects the value in radians. If your geometry is a little rusty, a full circle is 360° or 2
p
radians.

In Javascript you can use the
Math.PI
property to get the value of
p
(Pi). For example, 30° is 1/12 of a full circle so

you can write this as (
Math.PI*2/12)
.

Note

You can use multiple transformations. For example, you can translate the origin and then rotate the x/y axis.

You can also rotate the grid some more and translate again. Each transformation is always relative to the current

position and orientation.