Transformation in Canvas
Canvas transformations let you move, rotate, or scale the entire drawing area, making it easier to create dynamic and flexible graphics. These transformations affect everything drawn afterward unless reset.
1. Translate
The translate(x, y) method moves the canvas coordinate system to a new origin.
Use Case:
When you want to shift the drawing position without manually changing each coordinate.
Syntax:
Example:
Output:
.webp)
Example:
Output:
.webp)
Example:
Output:
.webp)
The translate(x, y) method moves the canvas coordinate system to a new origin.
Use Case:
When you want to shift the drawing position without manually changing each coordinate.
Syntax:
context.translate(x, y);
Example:
<canvas id="myCanvas" width="500" height="400"></canvas><script> const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d');
// Draw original square context.fillStyle = 'blue'; context.fillRect(110, 50, 100, 100);
// Move the canvas origin context.translate(200, 120);
// Draw translated square context.fillStyle = 'red'; context.fillRect(50, 50, 100, 100);</script>
Output:
.webp)
2. Rotate
The rotate(angle) method rotates the canvas around its origin (top-left corner or a new origin if translated).
Use Case:
Perfect for spinning objects or rotating graphics like a clock hand.
Syntax:
The rotate(angle) method rotates the canvas around its origin (top-left corner or a new origin if translated).
Use Case:
Perfect for spinning objects or rotating graphics like a clock hand.
Syntax:
context.rotate(angleInRadians);
Note: Math.PI radians = 180°. For example, 0.785 ≈ 45°.
Example:
<canvas id="myCanvas" width="500" height="400"></canvas><script> const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d');
// Move origin to center context.translate(canvas.width / 2, canvas.height / 2);
// Rotate the canvas 45 degrees context.rotate(0.785);
// Draw rotated square context.fillStyle = 'green'; context.fillRect(-50, -50, 100, 100);</script>
Output:
.webp)
3. Scale
The scale(x, y) method resizes drawings on the canvas by a scaling factor.
Use Case:
Useful for zoom effects or resizing elements without changing their actual dimensions.
Syntax:
The scale(x, y) method resizes drawings on the canvas by a scaling factor.
Use Case:
Useful for zoom effects or resizing elements without changing their actual dimensions.
Syntax:
context.scale(xScale, yScale);
- 1 = no change
- 2 = double size
- 0.5 = half size
Example:
<canvas id="myCanvas" width="500" height="400"></canvas><script> const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d');
// Original square context.fillStyle = 'purple'; context.fillRect(50, 50, 100, 100);
// Scale the canvas context.scale(2, 0.5);
// Draw scaled square context.fillStyle = 'orange'; context.fillRect(50, 50, 100, 100);</script>
Output:
.webp)