Loading

Transformation in Canvas

  • Translate: Moves the canvas and its origin to a different point. 

Syntax:

.translate(x,y)

Example:

<canvas id="myCanvas" width="500" height="400"></canvas>
 <script>
   const canvas = document.getElementById('myCanvas');
   const context = canvas.getContext('2d');
    
   context.fillStyle = 'blue';
   context.fillRect(110, 50, 100, 100);
    
   context.translate(200, 120);
     
  context.fillStyle = 'red';
   context.fillRect(50, 50, 100, 100);
 
 </script>

Output:


 

  • Rotate: Rotate the canvas around the current origin.

Syntax:

.rotate(angle)

Example:

<canvas id="myCanvas" width="500" height="400"></canvas>
  <script>
    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    
    context.translate(canvas.width / 2, canvas.height / 2);
    
    context.rotate(0.785);
    
    context.fillStyle = 'green';
    context.fillRect(-50, -50, 100, 100);
  </script>

Output:


  • Scale: Scales the canvas horizontally and vertically.

Syntax:

.scale(x, y)

Example:

<canvas id="myCanvas" width="500" height="400"></canvas>
  <script>
      const canvas = document.getElementById('myCanvas');
      const context = canvas.getContext('2d');

      context.fillStyle = 'purple';
      context.fillRect(50, 50, 100, 100);

      context.scale(2, 0.5);

      context.fillStyle = 'orange';
      context.fillRect(50, 50, 100, 100);
  </script>

Output: