Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 0.3 — Two Ways to Draw: SVG and Canvas
Data Visualization · Example 2 of 3

What is under the mouse?

The browser can draw in two ways. SVG keeps every shape as an element you can find, style and click. Canvas paints pixels and forgets the shapes. Each is best at different jobs, and good chart developers use both.

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 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Add a second circle to both drawings in the first example (SVG: a new <circle> tag; Canvas: another beginPath/arc/fill). Then log how many elements each contains.

02

In the second example, write insideRect(x, y) for a rectangle drawn with ctx.fillRect(70, 20, 30, 40), and test (80, 30) and (60, 30).

Explain it without notes

01

Explain the difference between SVG and Canvas to someone who has never coded.

02

Why does the canvas circle look blurry when zoomed, but the SVG one doesn't?

03

You need a chart of 300 stations that people can click. Which would you choose, and why?

04

You need to draw every trip of a year (about 300,000 lines) and redraw it while panning. Which would you choose, and why?

What is under the mouse?

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

SVG, on the circle: circle
SVG, on empty space: svg
Canvas, on the circle: CANVAS
Canvas, on empty space: CANVAS
Is (40, 40) inside the canvas circle? true
Is (100, 10) inside the canvas circle? false