Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Rotate HTML5 Canvas around the current origin
HTML5 canvas provides the rotate(angle) method which rotates the canvas around the current origin point. This method is essential for creating rotated graphics and animations.
Syntax
context.rotate(angle);
Parameters
The method takes one parameter:
- angle: The rotation angle in radians (clockwise direction)
To convert degrees to radians, use: radians = degrees * (Math.PI / 180)
Basic Rotation Example
Here's a simple example showing how to rotate a rectangle:
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid #000;
margin: 20px;
}
</style>
</head>
<body>
<canvas id="rotateCanvas" width="300" height="200"></canvas>
<script>
const canvas = document.getElementById('rotateCanvas');
const ctx = canvas.getContext('2d');
// Move origin to center
ctx.translate(150, 100);
// Rotate 45 degrees (Math.PI/4 radians)
ctx.rotate(Math.PI / 4);
// Draw rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(-50, -25, 100, 50);
</script>
</body>
</html>
Complex Rotation Pattern
This example creates a colorful spiral pattern using multiple rotations:
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid #000;
margin: 20px;
display: block;
}
</style>
</head>
<body>
<canvas id="spiralCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('spiralCanvas');
const ctx = canvas.getContext('2d');
// Move to center
ctx.translate(200, 200);
// Create spiral pattern
for (let i = 1; i < 7; i++) {
ctx.save();
ctx.fillStyle = `rgb(${51*i}, ${200-51*i}, 0)`;
for (let j = 0; j < i * 6; j++) {
ctx.rotate(Math.PI * 2 / (i * 6));
ctx.beginPath();
ctx.arc(0, i * 12.5, 5, 0, Math.PI * 2, true);
ctx.fill();
}
ctx.restore();
}
</script>
</body>
</html>
Key Points
- Rotation happens around the current origin (0,0)
- Use
translate()to move the origin before rotating - Always use
save()andrestore()to preserve transformation state - Angles are measured in radians, not degrees
- Positive angles rotate clockwise
Conclusion
The rotate() method is powerful for creating rotated graphics and animations. Combine it with translate() and save()/restore() for precise control over canvas transformations.
Advertisements
