Two sizes, the context, and what erases a canvas
Edge cases in one example: no size, CSS-only size (a stretched oval), bad width values, and a context that is null.
A canvas is one page element holding a grid of pixels, and the context is the pen you paint on it with. It has two sizes, the grid and the box, and it forgets every shape the moment it is painted.
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 setSize(canvas, w, h) that sets the grid size and returns the context, throwing a clear error when w or h is not a positive number.
Write paintSquares(ctx, counts) that clears the canvas, then paints one 10-pixel square per entry in counts in a row, painting a "No data" sentence when counts is empty.
Explain it without notes
What are the canvas's two sizes, and what happens if they differ?
Why does a canvas have no "update this bar" operation?
What does canvas.width = canvas.width do?
Preview
Console
Nothing logged yet.Expected console output
plain: 300 x 150
css: 300 x 150 shown in a box 240 x 60
inside the square: [ 42, 157, 143, 255 ]
outside the square: [ 0, 0, 0, 0 ]
before width = 300: [ 0, 0, 0, 255 ]
after width = 300: [ 0, 0, 0, 0 ]
126.25 -> 126, abc -> 0, -5 -> 300, 0 -> 0
same context again: true
webgl on a 2d canvas: null
unknown type: null