Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.5 — Workers and OffscreenCanvas
Data Visualization · Example 2 of 2

OffscreenCanvas in a worker, with its failures

The worker is built from text, so it has no DOM, no d3 import (it has its own tiny random generator) and no base address for fetch. The two error lines are what this browser printed.

Your script, layout and painting share one thread, and a long loop freezes all three. A Web Worker runs code on another thread, and OffscreenCanvas lets that thread draw. You learn when this helps, how it fails and when it is not worth it.

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 canUseWorkerCanvas(canvas) that returns true only when OffscreenCanvas and transferControlToOffscreen both exist.

02

Make the first example's worker answer with the busiest station instead of the mean minutes. What goes in its message?

Explain it without notes

01

Why did the ticker move 0 times while the main thread parsed?

02

What can a worker not do, and how does it get data from the page?

OffscreenCanvas in a worker, with its failures

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

dots drawn in the worker: 200,000
main thread getContext after the transfer -> InvalidStateError: Failed to execute 'getContext' on 'HTMLCanvasElement': Cannot get context from a canvas that has transferred its control to offscreen.
worker fetch of a relative URL -> TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope': Failed to parse URL from /data/lumen/stations.csv