HTML5 Canvas Reference - translate()








The translate() method moves the (0,0) position on the canvas.

Browser compatibility

translate() Yes Yes Yes Yes Yes

JavaScript syntax

context.translate(x,y);

Parameter Values

Parameter Description
x Where to move x coordinates
y Where to move y coordinates




Example

The following code draws two rectangles with the same values but changes the coordinates in between.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
   canvas  = document.getElementById("canvas"); 
   ctx = canvas.getContext("2d");
<!--from  w  ww .j  a va2s. co  m-->
   ctx.fillRect(10, 10, 200, 50);
   ctx.translate(100, 100);
   ctx.fillRect(10, 10, 200, 50);

</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code moves (0,0) position on canvas and then does rotation for 90 degrees.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
   canvas  = document.getElementById("canvas"); 
   ctx = canvas.getContext("2d");
<!--  w  ww .  j  a  v  a2s  .  c  o m-->
    ctx.save();
    ctx.translate(20, 50);
    ctx.rotate(-Math.PI / 2);
    ctx.fillText("java2s.com", 0, 0);
    ctx.restore();

</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code rotates an image in animation.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
    var ship = new Image();
    ship.src="http://www.java2s.com/style/download.png"
    ship.onload = function(){<!--from   w  w  w  .ja  va 2s.  c  om-->
       this.ready=true;
    }
    var stage= document.getElementById('canvas');
    var ctx = stage.getContext('2d');
    var degs=1;
    var draw= function(){
        ctx.save();
        ctx.translate(200,100);//ship x, y
        ctx.rotate(degs/100);
        ctx.translate(-ship.width/2,-ship.height/2);
        ctx.drawImage(ship,0,0);  
        ctx.restore();
        degs++;
    }
    setInterval(function(){draw()},16);

</script>
</body>
</html>

The code above is rendered as follows: