Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.4 — Dark Mode and Theme Tokens
Data Visualization · Example 2 of 2

Canvas and exported images do not follow CSS

Failure cases, each silent: an invalid canvas colour is ignored (the old #123456 stays), a canvas does not repaint when the class changes (the pixel is still #1f7a6f), and an SVG drawn as an image has no access to the page's variables, so its fill is black (#000000). In the picture the four bars are the dark theme's teal on a dark background, because the code ended in dark mode.

Put every chart colour in CSS custom properties (tokens), draw SVG with var() and currentColor, and a theme becomes one switch with no redraw. Canvas and exported images do not read CSS, so they must be given the resolved colour and redrawn.

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 a repaint function that clears the canvas from the second example and draws the bars with the current --chart-accent, and call it from a button that toggles the dark class.

02

List which parts of the dashboard in Phase 7 hold a hard-coded colour (open stations-bar.js) and say which token each should use.

Explain it without notes

01

Why does an SVG chart that uses var(--chart-accent) change theme with no redraw?

02

What happens to ctx.fillStyle = "var(--chart-accent)", and how do you colour a canvas by token?

03

Why do you need both @media (prefers-color-scheme: dark) and a data-theme rule?

Canvas and exported images do not follow CSS

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

fillStyle after assigning var(--chart-accent): #123456
bars drawn with the variable are: #123456
light theme, token #1f7a6f -> pixel #1f7a6f
class changed, canvas not redrawn -> pixel #1f7a6f
dark theme, redrawn with token #4fd1c0 -> pixel #4fd1c0
SVG drawn as an image, fill var(--chart-accent) -> #000000