Thursday, May 26, 2011

Translate canvas

To translate HTML5 canvas
  • Apply setTransform() before drawing
  • setTransform() with a identity matrix - (1,0,0,1,0,0)
  • call translate with the translation distance in the horizontal and vertical direction
  • draw!


example:
- without Translate
without Translate

- with Translate
with Translate

function canvasloader(){
var mycanvas = document.getElementById("canvas");
var mycontext = mycanvas.getContext("2d");
mycontext.fillStyle = "#0000ff";
mycontext.fillRect(0, 0, 150, 100);
doTransform(mycontext);
drawPath(mycontext);

}

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

}

function doTransform(context){
context.setTransform(1,0,0,1,0,0); //identity matrix
context.translate(100, 100);
}

No comments:

Post a Comment