Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.4 — Sharp Canvas on High-DPI Screens
Data Visualization · Example 2 of 2

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.

01

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?

02

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

01

Why is a canvas blurry on a phone, and an SVG not?

02

What are the three steps of a sharp canvas setup?

03

Why does a resize need a redraw?

Resizing erases the canvas, and scale() adds up

Preview

Press Run to see the page.

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