Immediate mode: clear, then paint it all again
The same function handles a normal week, zeros, an empty array and one value. Press the button to see each picture.
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
week 1: 7 values, 7 bars painted
week 2: 7 values, 3 bars painted
week 3: 0 values, 0 bars painted
week 4: 1 values, 1 bars painted
child elements in the canvas: 0
pixel at the top of Tuesday's bar: [ 42, 157, 143, 255 ]