Falcon80 Logo
2-D Rotation on canvas

Rotating an image is not fully straight forward and slightly tricky. The rotate() method rotates the canvas by the number of degrees you pass as parameter. The degrees should be mentioned in radians. This means, any image on the canvas is rotated about the origin of the canvas which is at (0,0).

2-D Rotation
Note that on a canvas, you have only the fourth quadrant visible and hence you will see the rotated image only if it falls within this quadrant.

2-D Rotation 

If you want to rotate an image about any point other than the origin, you will have to essentially translate the image to the origin, rotate it and then move it back to the point.

Note: It is important to remember that in canvas, the last transformation that you write is executed first. So if you are making a bunch of transformations, you have to write them in reverse order. In the above scenario where you are rotating an image around a point other than the origin, your code should read:


move the image back to its original location
rotate the image
move the image to the origin

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

// Let's load two images, flower.png and dove.png
var flower = new Image();
flower.src = "../../Images/Transformations/flower.png";
var dove = new Image();
dove.src = "../../Images/Transformations/dove.png";

for(i=0;i<=6.2; i+=0.1)
{
// We will now rotate the flower image .1 radians for the duration of the for loop. Note // that we are not translating the image to the origin. So the image will rotate around // the origin in this case
ctx.rotate(0.1);
ctx.drawImage(flower,100,0);
}

//Let's draw the dove image at a specific point around which we want to rotate it.
ctx.drawImage(dove,450,0);

// we will now translate the dove image to the origin first, rotate it by .7 radians and
// then translate it back to the original location. Note that I have given the
// transformation instructions in reverse order.

ctx.translate(450,0);
ctx.rotate(0.7);
ctx.translate(-450,0);
ctx.drawImage(dove,450,0);

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