Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.2 — D3 Drawing to Canvas
Data Visualization · Example 1 of 2

Line, axis, arc and map on one canvas

Every scale is the same code you wrote for SVG. The doughnut shows the e-bike share of the year's rides, and the small square is a made-up outline, only to show geoPath with a context.

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.

01

Draw a pale teal area under the line of the first example with d3.area() and a context. Which two things must you add?

02

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

01

What does d3.line().context(ctx) return when you call it, and why?

02

Why can you not use d3.axisBottom on a canvas, and what do you use instead?

Line, axis, arc and map on one canvas

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

line(rows) with a context returns: undefined
the same generator without a context returns a string of length: 5419
days drawn: 365 - e-bike share of rides: 33.3%