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
translate_rotate.html · full logical source
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>
  1. Save the current drawing state

    kf: 1event 0kind: lifecycle

    Save the current drawing state.

    4ctx.save→ one saved state();
    The canvas is blank while the state is saved.
    save remembers the current transform and paint state.
    State after this keyframeempty → one saved statestate stack
  2. Move the origin to the canvas center

    kf: 2event 1kind: lifecycle

    Move the origin to the canvas center.

    5ctx.translate→ 180,110(180, 110);
    The canvas is still blank after moving the coordinate system.
    translate changes where future coordinates are measured from.
    State after this keyframe0,0 → 180,110origin
  3. Rotate the coordinate system

    kf: 3event 2kind: lifecycle

    Rotate the coordinate system.

    6ctx.rotate→ -0.28 rad(-0.28);
    The canvas remains blank until a draw call uses the rotated axes.
    rotate affects future drawing, not existing pixels.
    State after this keyframe0 → -0.28 radrotation
  4. Draw a rectangle in the transformed coordinate system

    kf: 4event 3kind: lifecycle

    Draw a rectangle in the transformed coordinate system.

    8ctx.fillRect→ rotated card(-70, -32, 140, 64);
    An amber rectangle appears tilted around the center.
    The fillRect coordinates are interpreted after translate and rotate.
    State after this keyframeblank → rotated cardvisible pixels
  5. Restore the original drawing state

    kf: 5event 4kind: lifecycle

    Restore the original drawing state.

    9ctx.restore→ original transform();
    The rotated rectangle stays while future drawing state returns to normal.
    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.