Resizing erases the canvas, and scale() adds up
Edge cases: a resize that erases, a scale that multiplies, and a fractional ratio.
On a phone or a retina laptop one CSS pixel is two or three device pixels, so a canvas sized in CSS pixels is stretched and blurry. The fix is a bigger pixel grid in the same box, with the context scaled once.
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.
Write fitCanvas(canvas, ratio) that reads the box size from canvas.getBoundingClientRect() and sets up the grid for the given ratio. What must the caller do after it?
Explain why a 3-pixel line at y = 30 is crisp at ratio 1 only if you draw it at y = 30.5.
Explain it without notes
Why is a canvas blurry on a phone, and an SVG not?
What are the three steps of a sharp canvas setup?
Why does a resize need a redraw?
Preview
Console
Nothing logged yet.Expected console output
after setup at ratio 2: scale 2 | pixel inside a bar: 255
after canvas.width = 640: scale 1 | pixel inside a bar: 0
after setup + draw at 320 x 100: pixel inside a bar: 255
scale() in the draw function, 3 redraws: 2, 4, 8
setTransform once, 3 redraws: 2, 2, 2
ratio 1.25 on 101 px: backing store 126 -> real scale 1.2475