Wednesday, May 25, 2011

Rotate canvas

To rotate HTML5 canvas
- Apply setTransform() before drawing
- setTransform() with a identity matrix - (1,0,0,1,0,0)
- call rotate with clockwise rotation angle expressed in radians
- draw!

example:
- without rotate:
without rotate
- with rotate:
with rotate

function canvasloader(){
var mycanvas = document.getElementById("canvas");
var mycontext = mycanvas.getContext("2d");
mycontext.fillStyle = "#A0A0A0";
mycontext.fillRect(10, 10, 300, 220);
mycontext.fillStyle = "#00ff00";
mycontext.fillRect(20, 20, 200, 100);
mycontext.fillStyle = "#0000ff";
mycontext.fillRect(200, 100, 100, 100);
doTransform(mycontext);
drawPath(mycontext);

}

function drawPath(context){
context.strokeStyle = "#000000";
context.lineWidth = 10;
context.beginPath();
context.moveTo(50, 50);
context.lineTo(150, 50);
context.lineTo(150, 100);
context.lineTo(50, 100);
context.closePath();
context.stroke();

}

function doTransform(context){
context.setTransform(1,0,0,1,0,0); //set transformation matrix as identity matrix
var rotateAngle = 45 * Math.PI/180; //clockwise rotation angle expressed in radians
context.rotate(rotateAngle);
}

No comments:

Post a Comment