HTML and CSS Reference
In-Depth Information
Figure 2-13. Rotation and the Canvas state
The small black square was unaffected by the rotation, so you can see that only the shapes
drawn after the context.rotate() function was called were affected.
did not know what origin to use for the rotation. In the absence of an actual translated ori-
gin, 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 center
Let's change Example 2-8 to rotate the red square 45 degrees while keeping it in its current
First, we take the numbers we applied to the fillRect() function call to create a few vari-
ables 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,usingthe context.translate() functioncall,wemustchangetheoriginofthecanvas
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:
Search WWH ::

Custom Search