The grid for every ratio, and half-pixel lines
The ratio is a parameter, because the checker's screen always has ratio 1. On your device, pass window.devicePixelRatio.
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
ratio 1: CSS box 101 x 40 -> backing store 101 x 40
ratio 2: CSS box 101 x 40 -> backing store 202 x 80
ratio 3: CSS box 101 x 40 -> backing store 303 x 120
ratio 1.5: CSS box 101 x 40 -> backing store 152 x 60
ratio 1.25: CSS box 101 x 40 -> backing store 126 x 50
fillRect(10, 10, 140, 1), rows 9, 10, 11 -> alpha 0, 255, 0
stroke at y = 30, rows 29, 30, 31 -> alpha 127, 128, 0
stroke at y = 50.5, rows 49, 50, 51 -> alpha 0, 255, 0