HTML and CSS Reference
We will need to draw the object starting with the correct upper-left coordinates for x
and y . We do this by subtracting half the width of our object from the origin x , and half
the height of our object from the origin y :
context.fillRect(-0.5*width,-0.5*height, width, height);
Why do we do this? Figure 2-14 illustrates the situation.
Consider that we want to draw our square starting at the top-left corner. If our origin
point is at 125,125, the top left is actually 100,100. However, we have translated our
origin so the canvas now considers 125,125 to be 0,0. To start our box drawing at the
nontranslated canvas, we have to start at -25,-25 on the “translated” canvas.
This forces us to draw our box as though the origin is at 0,0, not 125,125. Therefore,
when we do the actual drawing of the box, we must use these coordinates, as shown
in Figure 2-15 .
Figure 2-14. The newly translated point
Figure 2-15. Drawing with a translated point
In summary, we needed to change the point of origin to the center of our square so it
would rotate around that point. But when we draw the square, we need our code to
act as though the (125,125) point is actually (0,0). If we had not translated the origin,
we could have used the (125,125) point as the center of our square (as in Fig-
ure 2-14 ). Example 2-9 demonstrates how this works, creating the result shown in
Figure 2-16 .