HTML and CSS Reference
In-Depth Information
Again, the red box was moved far off to the left. To reiterate, this occurred because the
canvas did not know what origin to use for the rotation. In the absence of an actual
translated origin, the 0,0 position setting is applied, resulting in the context.rotate()
function rotating “around” the 0,0 point, which brings us to our next lesson.
Lesson 2: We must “translate” the point of origin to the center of our shape to rotate it around its own
Let's change Example 2-8 to rotate the red square 45 degrees while keeping it in its
current location.
First, we take the numbers we applied to the fillRect() function call to create a few
variables to hold the red square's attributes. This is not necessary, but it will make the
code much easier to read and change later:
var x = 100;
var y = 100;
var width = 50;
var height = 50;
Next, using the context.translate() function call, we must change the origin of the
canvas to be the center of the red square we want to rotate and draw. This function
moves the origin of the canvas to the accepted x and y locations. The center of our red
square will now be the desired top-left corner x location for our object ( 100 ), plus half
the width of our object. Using the variables we created to hold attributes of the red
square, this would look like:
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:
The translate() function call looks like this:
context.translate(x+.05*width, y+.05*height)
Now that we have translated the canvas to the correct point, we can do our rotation.
The code has not changed:
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.
Search WWH ::

Custom Search