HTML Canvas - rotate() Method



The HTML Canvas rotate() method rotates available graphic to which context object is used at a certain angle for the transformation matrix.

Syntax

Following is the syntax of HTML Canvas restore() method −

CanvasRenderingContext2D.rotate(angle);

Parameters

Following is the parameters used by this method −

S.No Parameter & Description
1

angle

The angle in radians to which the context object is to be rotated.

Return value

It returns a rotated transform object which is used by the CanvasRenderingContext2D object.

Example

The following example takes a line drawn on the Canvas and rotates it at a certain angle passed as parameter to the HTML Canvas rotate() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.moveTo(25, 25);
      context.lineTo(150, 25);
      context.stroke();
      context.closePath();
      context.beginPath();
      context.rotate(18 * Math.PI / 180);
      context.moveTo(100, 100);
      context.lineTo(225, 100);
      context.stroke();
      context.closePath();
   </script>
</body>
</html>

Output

The output returned by the following code on the webpage as −

HTML Canvas Rotate method

Example

The following example rotates a square drawn on the Canvas element using the method rotate().

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="450" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.strokeRect(25, 20, 150, 100);
      context.rotate(50 * Math.PI / 180);
      context.strokeRect(250, 10, 150, 100);
   </script>
</body>
</html>

Output

The output returned by the following code on the webpage as −

HTML Canvas Rotate method
html_canvas_shadows_and_transformations.htm
Advertisements