rotate(angle) adds a clockwise rotation to the current Canvas transformation matrix. The angle is measured in radians, and rotation happens around the current origin.
const angle = 30 * Math.PI / 180;
ctx.save();
ctx.rotate(angle);
ctx.fillRect(80, 20, 140, 45);
ctx.restore();
const radians = degrees * Math.PI / 180;
ctx.rotate(radians);
Canvas rotates around the origin. To rotate around a rectangle center, translate to the center, rotate, draw the rectangle around local coordinates, and restore.
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(45 * Math.PI / 180);
ctx.fillRect(-width / 2, -height / 2, width, height);
ctx.restore();
Each rotate() call modifies the current transformation matrix. Repeated clicks in the legacy example kept rotating because the transform was never restored. Prefer save()/restore() for isolated drawings.
Positive angles rotate clockwise in the Canvas coordinate system.
No. The angle is in radians.
The default origin is at (0,0). Translate to the intended pivot before rotating.
Use save() before the transform and restore() afterward, or resetTransform() when appropriate.
No. It affects subsequent drawing operations through the transformation matrix.
translate() | transform() | Canvas tutorial
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.