Falcon80 Logo
2-D Translation of images on canvas

You can shift an image anywhere across the canvas using the translate() method. Suppose you have an image at position (x,y) and would like to move it to (x1,y1). The translate() method will do this for you. The method takes in two parameters:

1. The number of pixels the image has to be moved in the x-direction
2. the number of times the image has to be movied in the y-direction

Both the parameters are float values.

So for example, if you are drawing an image at (10,10) using the drawImage() method. If you had used the translate() method before the drawImage() method with parameters (100,10), then the final image will be drawn at the position (100+10, 10+10) = (110, 20).

The translate() method, combined with other transformations can be a very powerful tool in animation.

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");

// Create a new image object
var flower = new Image();

//Provide the source directory of the image you are about to upload
flower.src = "flower.png";

// Move the image by 200 pixels in the x-direction
ctx.translate(200, 0);

// Note that we are drawing the image at (150,0). However, when the code is executed, //the image will be drawn at (150 + 200, 0 + 0) = (350,0)
ctx.drawImage(flower, 150, 0);

}
}
  </script>
  <title>Translating an image on canvas</title>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code