Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.5 — Responsive Charts
Data Visualization · Example 2 of 3

A resize storm: a plain observer and onResize

The same measuring code as src/utils/resize.js, pasted in. A plain observer redraws once per change, including for a height-only change that needs no redraw. onResize draws once at the start and once after the drag stops, ignores the height-only change, and does nothing after stop().

A chart can scale (one drawing, stretched by its viewBox) or redraw (a new drawing at the real width). Scaling is free but shrinks the text. Redrawing keeps text readable and lets you choose fewer ticks and shorter labels, at the cost of watching the box with a ResizeObserver, and of not redrawing on every pixel.

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

Write onWidthClass(element, callback) that calls callback(cls) only when the size class changes (small, medium, large), using ResizeObserver and the sizeClass function.

02

The stations bar chart has fixed 20 pixel rows. At 300 pixels wide, which part of it breaks first, and what would you change in drawStationsBar?

Explain it without notes

01

When is scaling with the viewBox enough, and when should a chart redraw?

02

Why use a ResizeObserver instead of window.resize?

03

How does onResize avoid a redraw on every frame of a drag?

A resize storm: a plain observer and onResize

Console

(nothing was printed)

Expected console output

first report:                       plain 1 | onResize 1
after 10 changes, while dragging:   plain 11 | onResize 1
after the changes stop:             plain 11 | onResize 2
after a height-only change:         plain 12 | onResize 2
after stop() and one more change:   plain 13 | onResize 2