HTML and CSS Reference
In-Depth Information
x + 0.5 * width
Next, we must find the y location for the origin translation. This time, we use the y value of
the top-left corner of our shape and the height of the shape:
y + 0.5 * height
The translate() function call looks like this:
context . translate ( x + 0.5 * width , y + 0.5 * height )
Now that we have translated the canvas to the correct point, we can do our rotation. The code
has not changed:
context . rotate ( angleInRadians );
Finally, we need to draw our shape. We cannot simply reuse the same values from
Example 2-8 because the canvas origin point has moved to the center of the location where
we want to draw our object. You can now consider 125,125 as the starting point for all draw
operations. We get 125 for x by taking the upper-left corner of the square ( 100 ) and adding
half its width ( 25 ). We do the same for the y origin position. The translate() method call
accomplishes this.
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 that the
canvasnowconsiders125,125tobe0,0.Tostartourboxdrawingatthenontranslated canvas,
we have to start at −25,−25 on the “translated” canvas.
Thisforcesustodrawourboxasthoughtheoriginisat0,0,not125,125.Therefore, whenwe
do the actual drawing of the box, we must use these coordinates, as shown in Figure 2-15 .
Search WWH ::

Custom Search