Rotate object or shape in HTML5 Canvas

HTML5 canvas provides rotate(angle) method which is used to rotate the canvas around the current origin clockwise. The parameter ‘angle’ should be radians not in degrees. You can use degree * Math.PI/180 formula to convert the degree in radians, suppose if you want to rotate canvas 45 degree you can use 45*Math.PI/180 for the angle.

One more thing this is also important that the rotation center point is always the canvas origin but you can change the rotation center points by using the translate() method.

In the below example we are changeing rotation center point to center of canvas and than rotate 45 degree.

<!DOCTYPE HTML>
<html>
  <head>
  <style>
  #myCanvas{
  border:1px solid #bbb;
  }
  </style>
  </head>
  <body>
    <canvas id="myCanvas" width="400" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var ctx = canvas.getContext('2d');
      var recWidth = 200;
      var recHeight = 100;
 
      ctx.translate(canvas.width/2, canvas.height/2);
 
      // rotate 45 degrees clockwise
      ctx.rotate(Math.PI/4);
 
      ctx.fillStyle = 'red';
      ctx.fillRect(recWidth/-2, recHeight/-2, recWidth, recHeight);
    </script>
  </body>
</html>

The above example would produce following result −

Rotate a rectangle in HTML5 canvas
Rotate a rectangle in HTML5 canvas

You can also produce a animation by rotating canvas continuously, see the below example:

<!DOCTYPE HTML>
<html>
<head>
    <style>
        #myCanvas {
            border: 1px solid #bbb;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var rectWidth = 150;
        var rectHeight = 30;
        var angle = 0;
 
        // translate context to center of canvas
        function rotateRect() {
            context.translate(canvas.width / 2, canvas.height / 2);
            context.rotate(angle);
 
            context.fillStyle = 'red';
            context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
            if (angle >= 3.14) {
                angle = 0;
            }
            angle = angle + .10;
        }
 
        function moveRectangle() {
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.save();
            rotateRect()
            context.restore();
        }
        var loop = setInterval(moveRectangle, 100);
    </script>
</body>
</html>

setInterval() method calls the moveRectangel() function at every 100 milliseconds until clearInterval() is called, or the window is closed. So you have control over this animation, You can stop and start according to you. Like:

var loop = setInterval(moveRectangle, 100);
 
function stopRotation() {
    clearInterval(loop);
}