Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.3 — Transforms and the State Stack
Data Visualization · Example 1 of 2

The transform that leaks into every later draw

A failure with no error: the left canvas shows only two of three markers, the second one in the wrong place.

translate, rotate and scale move the canvas's grid instead of your shapes, and every one of them stays set until you undo it. save and restore are how you undo them, and forgetting that is the source of most canvas surprises.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 4 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Draw five 20 × 20 squares in a row, 30 pixels apart, using translate and save/restore so that no change leaks.

02

Draw a 40-pixel-long line that spins around its middle by 45 degrees, centred at (100, 50).

Explain it without notes

01

Why does drawing three markers with translate and no restore put marker 3 off the canvas?

02

What does save() save, and what does restore() not bring back?

03

How do translate then rotate differ from rotate then translate?

The transform that leaks into every later draw

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

a: after drawing, the origin is at (240, 90)
b: after drawing, the origin is at (0, 0)
scale(2, 2) call 1: the matrix scales by 2
scale(2, 2) call 2: the matrix scales by 4
scale(2, 2) call 3: the matrix scales by 8
after setTransform(1, 0, 0, 1, 0, 0): 1