State and Transforms
Translate and Rotate
The context saves state, translates and rotates the coordinate system, draws a card, then restores the original state.
Program
Canvas transforms affect future drawing calls. save and restore keep temporary transforms from leaking into later drawing.
translate_rotate.html
Visuals: generated teaching cards from captured state
- state written by this keyframe
1<canvas id="stage" width="360" height="210"></canvas>
2<script>
3 const ctx = stage.getContext("2d");
4 ctx.save();
5 ctx.translate(180, 110);
6 ctx.rotate(-0.28);
7 ctx.fillStyle = "#f59e0b";
8 ctx.fillRect(-70, -32, 140, 64);
9 ctx.restore();
10</script>Save the current drawing state
kf: 1event 0kind: lifecycleSave the current drawing state.
4ctx.save→ one saved state();
save remembers the current transform and paint state. State after this keyframeempty → one saved statestate stackMove the origin to the canvas center
kf: 2event 1kind: lifecycleMove the origin to the canvas center.
5ctx.translate→ 180,110(180, 110);
translate changes where future coordinates are measured from. State after this keyframe0,0 → 180,110originRotate the coordinate system
kf: 3event 2kind: lifecycleRotate the coordinate system.
6ctx.rotate→ -0.28 rad(-0.28);
rotate affects future drawing, not existing pixels. State after this keyframe0 → -0.28 radrotationDraw a rectangle in the transformed coordinate system
kf: 4event 3kind: lifecycleDraw a rectangle in the transformed coordinate system.
8ctx.fillRect→ rotated card(-70, -32, 140, 64);
The fillRect coordinates are interpreted after translate and rotate. State after this keyframeblank → rotated cardvisible pixelsRestore the original drawing state
kf: 5event 4kind: lifecycleRestore the original drawing state.
9ctx.restore→ original transform();
restore changes future drawing state without erasing existing pixels. State after this keyframetemporary transform → original transformstate stack
translate
translate moves the origin for future drawing.
save/restore
save and restore bracket temporary drawing state changes.