A canvas chart with its own state, and its edge cases
Press the buttons. A generator's context is only an object with moveTo, lineTo and closePath: the recorder counts the pen's moves, so each case is checked without looking at pixels.
D3's scales, shapes and geo paths work without SVG. Give a shape generator a canvas context and it draws instead of returning a string. What you lose is the data join: on canvas you keep your own state and redraw it all.
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.
Draw a pale teal area under the line of the first example with d3.area() and a context. Which two things must you add?
Write drawTicks(ctx, scale, width) that draws a pale horizontal line at every tick of a linear scale and returns how many ticks it drew.
Explain it without notes
What does d3.line().context(ctx) return when you call it, and why?
Why can you not use d3.axisBottom on a canvas, and what do you use instead?
Preview
Console
Nothing logged yet.Expected console output
full moveTo 1 lineTo 364
gap moveTo 2 lineTo 332
one moveTo 1 lineTo 0
none moveTo 0 lineTo 0