The Essential Guide to HTML5

(Greg DeLong) #1

CANNONBALL AND SL INGSHOT


Figure 4-7. Drawing and rotating a rectangle


The problem is the rotation point is at the origin, (0,0) and not at the corner of the red rectangle. So, I need
to write code to perform a translation, then the rotation, then a translation back in order to draw at the
correct place. I can do this using features of HTML5. All drawing on the canvas is done in terms of a
coordinate system, and I can use the save and restore operations to save the current coordinate
system—the position and orientation of the axes—and then restore it to make follow-on drawings. Heres
the code.


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


The rotate method expects an angle in radian units and clockwise is the positive direction. So my code is
rotating 30 degrees counterclockwise, producing what I had in mind, as shown in Figure 4-8.


Figure 4-8. Save, translate, rotate, translate, restore

Free download pdf