SyntaxStudy
Sign Up
HTML Canvas Transformations
HTML Intermediate 5 min read

Canvas Transformations

Canvas Transformations

translate(), rotate(), and scale() transform the coordinate system for subsequent drawings. Always wrap transformations with save() and restore().

Example
const ctx = canvas.getContext("2d");

ctx.save();                      // Save current state

ctx.translate(200, 200);        // Move origin to center
ctx.rotate(Math.PI / 4);       // Rotate 45 degrees
ctx.fillStyle = "#dc3545";
ctx.fillRect(-50, -30, 100, 60); // Draw centered rectangle

ctx.restore();                   // Restore original state

// Next drawing is unaffected by the rotation
ctx.fillStyle = "#007bff";
ctx.fillRect(20, 20, 80, 80);
Pro Tip

Always pair save() with restore() around transformations — unpaired transforms accumulate and corrupt subsequent drawings.