Canvas Rotate

What You’ll Learn
ctx.rotate() rotates the canvas coordinate system. Everything you draw after that will be rotated.
The key idea is: rotation happens around the current origin (0,0). To rotate around a point, you translate to that point first.
⚡ Quick Reference
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(angleRad);
ctx.fillRect(-w / 2, -h / 2, w, h);
ctx.restore();radiansdegrees × (Math.PI / 180)
future drawingsTransforms persist until reset
save() / restore()Avoid accidental transformations
👀 Live Preview — Origin vs Center Rotation
Switch between rotating around the canvas origin (top-left) and rotating around the rectangle center. This makes it clear why translate() matters.
Tip: In the canvas coordinate system, positive rotation is clockwise because the y-axis points downward.
Rotate a Rectangle Around Its Center
This is the standard pattern: translate to the rotation point, rotate, then draw centered around (0,0).
const rectWidth = 100;
const rectHeight = 50;
const cx = canvas.width / 2;
const cy = canvas.height / 2;
const angle = 45 * (Math.PI / 180);
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(angle);
ctx.fillStyle = 'blue';
ctx.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
ctx.restore();Rotate an Image (Safe Transform Scope)
Use save()/restore() so the transform doesn’t leak into later drawings.
img.onload = () => {
const cx = canvas.width / 2;
const cy = canvas.height / 2;
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(Math.PI / 180 * 25);
ctx.drawImage(img, -img.width / 2, -img.height / 2);
ctx.restore();
};💡 Best Practices
Do
- Convert degrees to radians with
deg * (Math.PI / 180) - Translate to the rotation point before rotating
- Use
save()/restore()to scope transforms - Keep draw calls relative to (0,0) after translating
- Reset transforms in animation loops each frame
Don’t
- Call
rotate()repeatedly without resetting (it accumulates) - Forget that rotation is around the origin
- Assume clockwise/counterclockwise like math graphs (canvas y-axis flips it)
- Leave transforms active and wonder why later drawings are skewed
- Overdraw large canvases every frame without profiling
❓ Frequently Asked Questions
deg * (Math.PI / 180).save()/restore(), or reset the transform when you’re done.Next: Canvas Scale
Scale shapes and images, and learn how scaling affects line widths.
4 people found this page helpful
