Canvas Drawing State
Canvas Transform Stack
State Moves the Drawing Space
A canvas program saves drawing state, moves and rotates the coordinate system, draws a badge, restores state, and then writes text in the original space.
Program
Canvas transforms change the coordinate system for later drawing calls. Step through the source to see which operations change pixels and which only prepare state for the next draw.
canvas_transform_stack.js
const canvas = document.querySelector('#badge-canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#f8fafc';
ctx.fillRect(0, 0, 320, 200);
ctx.save();
ctx.translate(160, 100);
ctx.rotate(Math.PI / 8);
ctx.fillStyle = '#2563eb';
ctx.fillRect(-70, -40, 140, 80);
ctx.restore();
ctx.fillStyle = '#0f172a';
ctx.font = '700 28px sans-serif';
ctx.fillText('READY', 108, 110);
transform state
Canvas keeps transform state inside the drawing context. `translate()` and `rotate()` affect later coordinates.
save and restore
`save()` pushes the current drawing state, and `restore()` returns to that saved state.
drawing space
The same `fillRect()` call lands in a different place after the drawing space has been moved and rotated.
unrotated text
After `restore()`, text uses the original coordinate system again.