The Essential Guide to HTML5

(Greg DeLong) #1

CHAPTER 4


The result is shown in Figure 4-6.


Figure 4-6. Rectangle (no rotation)


In this exercise, the goal is to rotate the large rectangle, pivoting on the upper-left corner where the small
blue square is. I want the rotation to be counterclockwise.


One slight complication, common to most programming languages, is that the angle input for rotations as
well as the trigonometry functions must be in radians, not degrees. Radians were explained in Chapter 2,
but heres a reminder. Instead of 360 degrees in a full circle, the measurement is based on two times the
mathematical constant pi radians in a circle. Fortunately, we can use the built-in feature of JavaScript,
Math.PI. One pi radians is equivalent to 180 degrees and pi divided by 2 is equivalent to a right angle, 90
degrees. To specify a rotation of 30 degrees, we use pi divided by 6 or, in coding, Math.PI/6. To change
the init function given previously to do a rotation, I put in a rotation of negative pi divided by 6
(equivalent to 30 degrees going counterclockwise), draw the red rectangle, and then rotate back, undo the
rotation, to draw the blue square:


function init(){
ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = "rgb(250,0,0)";
ctx.rotate(-Math.PI/6);
ctx.fillRect(50,50,100,200);
ctx.rotate(Math.PI/6);
ctx.fillStyle = "rgb(0,0,250)";
ctx.fillRect(50,50,5,5);
}


Unfortunately, the drawing in Figure 4-7 is not what I wanted.

Free download pdf