Back to writing

Web Graphics

How the Sky Islands at the Top of This Site Work

A painted world in Canvas 2D with no images or libraries: layers, two web workers, and the rules that keep it fast and easy to play with.

· 5 min read

  • Canvas
  • Web Workers
  • Performance

The top of this site is a small world: a floating island with a lantern tree, a sea of clouds, whales, a mill, and a field guide that fills in as you look around. I wanted a home page that shows how I build things instead of only describing it. It also had to load like a normal page, which turned out to be the harder part.

No images, one seed

There are no image files in it. Every rock, leaf and cloud is drawn with the Canvas 2D API when the page loads. The randomness comes from a seeded generator, so it is the same island on every visit.

That kept the download small. The whole engine, with every scene and creature, is about 152 KB of gzipped JavaScript and uses no libraries. A painted background image at full resolution would usually weigh more than that, and it couldn't move.

Paint once, draw what moves

Most of the scene never changes: the sky, the far mountains, the ridges, the island's rock. Redrawing those every frame would waste nearly all the work. So the world is split into 16 stacked canvases. Ten are painted once for each size and theme, and after that they only slide, while the two that hold the light fade slowly up and down by CSS. The other six hold everything that moves, and only those are redrawn each frame.

export const LAYERS = [
  { d: 0, res: 0.6, paint: "sky" },
  { d: 0, res: 0.3, draw: "aurora" },
  { d: D_FAR, res: 0.5, paint: "far" },
  { d: D_BACK, res: 0.5, paint: "ridge" },
  { d: D_BACK, res: 0.8, draw: "back", half: "odd" },
  { d: 0.3, res: 0.5, paint: "mid" },
  { d: 0.3, res: 0.25, draw: "hillShade" },
  { d: 0.4, res: 0.5, paint: "flanks" },
  { d: D_ISLE, res: 1, paint: "island" },
  { d: D_ISLE, res: 0.25, draw: "shade" },
  { d: D_ISLE, res: 1, draw: "isle" },
  { d: 0.65, res: 0.45, paint: "front" },
  { d: 0.65, res: 0.3, paint: "rays", glow: "breathe" },
  { d: 0.65, res: 0.2, paint: "glow", glow: "warm" },
  { d: D_FRONT, res: 1, half: "even", draw: "front" },
  { d: 1, res: 0.3, paint: "fg" },
];

Each layer has a depth, d, which sets how far it slides with the pointer and how much it lags behind the page as you scroll. That alone gives the shadow-box look. Each layer also has its own resolution. The sky is a soft gradient, so it renders at 60% of full resolution. The dark ferns in the foreground are blurred anyway, so 30% is enough. The island, which is what you look at, gets all of it. A layer that only covers a band of the scene, like the wooded ridge, gets a canvas only that tall, so the browser has less to composite.

Here it is running, on the same renderer as the top of the home page. Take it apart to see the canvases: the six edged in gold are drawn every frame, and the rest were painted once. Pick a name to see that canvas alone.

Getting it off the main thread

The static layers were always painted in a web worker, which sends them back as ImageBitmaps that move between threads without being copied. On a device with more than two cores there are two paint workers: one paints the island, which is about half the work, and the other paints the rest. With the CPU slowed four times, that brings the world up about 30% sooner on a phone and about 17% sooner on a desktop. But the first version drew every frame on the page's main thread. Desktop Lighthouse scored it 97. Mobile Lighthouse, which slows the CPU down four times, scored it 61. The cost was the drawing, not the download.

A second worker fixed that. The render worker owns the canvases themselves: the page calls transferControlToOffscreen() on each one and hands it over, and from then on the worker draws every frame. The main thread reads the pointer and the scroll position, posts them across, and moves the finished layers with CSS transforms.

Browsers without OffscreenCanvas run the same renderer on the main thread. It sends and receives the same messages either way, so there is one renderer to test, and if the worker fails to start, the page falls back to it on fresh canvases.

After the move, mobile Lighthouse scores between 94 and 97 from run to run, desktop scores 99, and nothing shifts while the page loads. The largest contentful paint is my name in the header, not the world.

The theme switch

The world has two palettes: golden hour for the light theme and night for the dark one. My first theme switch repainted the static layers on the spot, which froze the page for about a second. Now the paint workers paint the other theme in the background as soon as the first one is up, so switching only swaps bitmaps. The change spreads out from the sun or the moon, using the View Transitions API with a soft circular mask.

When a device can't keep up

The renderer keeps a running average of how long frames take. If they run long for a while, it switches to a lite mode for the rest of the visit: the animated layers drop to a pixel ratio of 1, and the two busiest ones redraw on alternate frames, so no single frame carries both. If frames still run long after that, the animated layers drop again, to 70% of that resolution. Firefox on Linux needs this second step, because it draws canvases on the CPU, where the cost follows the number of pixels. It never switches back, because flipping in and out would be more noticeable than either mode.

If your system asks for reduced motion, the world draws once and holds still.

It works offline too. A small service worker keeps each page you visit and the files it used, the world's scripts included, and hands back the kept copy when there is no connection. Pages come from the network whenever it answers, so a new version shows straight away. Offline, the field guide tells you the trader can't fly today, and its letter waits for a day you're online.

Rules for touching it

I wanted it to be something you play with, without any instructions on screen. A few rules made that work:

  • Hovering only looks. It names a thing and may change it in place, but nothing moves out from under the cursor. A thing goes in the field guide once its name has been up for a moment, so sweeping past it on the way to a link doesn't count.
  • A click touches. It pops a bubble, pushes the swing or startles a fish in the clouds.
  • Not everything arrives at once. On a first visit the world opens with only places and weather, and the creatures arrive one at a time over about a minute.
  • The keyboard can play too. After the Sound button, Tab goes into the world. The arrow keys step from thing to thing, Enter or Space does what a click does, and each name is read out. After dark, Enter on a star starts joining up the stars, the arrow keys draw the line on from star to star, and Enter again finishes the constellation.

The hit tests behind the hover labels run in the render worker too, against the same shapes it draws, and the answer comes back with each frame. The arrow keys move between those same shapes, to the nearest one in the arrow's direction.

The world also follows your calendar. The lantern tree is a maple: through autumn its leaves turn red and orange, a few more every day from the start of September, and blow off it. They pile up round its trunk, and a quick sweep of the pointer through the pile sends them flying with a soft crunch. Click a leaf as it falls and you catch it: it is pressed in the field guide, and tucked into the corner of that autumn's postcards. In spring its seeds spin down like little helicopters, and a click sends one whirling back up. In winter snow falls and slowly settles on the tree while you watch. In the weeks real geese migrate, from mid-September to the end of November and again in March and April, a V of them crosses the high sky every few minutes, south or north, honking far off. Each week something small, a key or a teacup, falls off a passing trader's ship and lies in the grass until you find it. Pick it up and its owner sends a thank-you, which the field guide keeps in your own browser. On a few days it dresses up. In Halloween week the lanterns are pumpkins and some of the starlings are bats, and at New Year a click on the sky sets off a firework. The case studies have small painted scenes made with the same code, and the field guide can save a postcard of the view, postmarked with the date and season.

The night sky is the real one, over wherever you are. Its stars are the 903 brightest in the Yale Bright Star Catalogue, packed into about 4.5 KB. There is no location prompt: the server passes on the rough city your request came from, and the page works out the sidereal time, turns each star's position into a height and a direction, and draws the southern half of your sky (the northern half, south of the equator) through a fish-eye lens, so the constellations keep their shapes across a wide screen. The stars to join up are real ones, and hovering one names it. A constellation you draw stays pinned to its stars, so the next time you come back it has wheeled round the sky with them, or set. On the nights of a real meteor shower, the Perseids in August, the Geminids in December and six others through the year, the shooting stars come thick and fast, strongest on the shower's peak night, and each one flies out of the shower's radiant, from where that point really is in your sky. While the radiant is below your horizon there is no shower to see, just as outside. A click on a shooting star catches it, and it falls into the firefly jar as a tiny star.

The weather is yours too. The page sends the same rough place to a small route on this site, which asks Open-Meteo for the weather there and caches the answer for a quarter of an hour, so the place goes no further than this site. When it is raining where you are, it rains right across the world, and the shy bells open where it lands. Snow falls, fog fills the valleys behind the island, a thunderstorm lights up the sky beyond the far hills and rumbles a few seconds later, and a windy day sends the gusts across more often. Hovering the open sky says so. Weather data by Open-Meteo.com (opens in a new tab), under CC BY 4.0 (opens in a new tab).

So are the northern lights. Another route asks NOAA's Space Weather Prediction Center (opens in a new tab) for the planetary K index, a number from 0 to 9 for how disturbed the Earth's magnetic field is, which it estimates every minute. That number is the same for everyone, so nothing about you is sent to get it. The page works out your magnetic latitude from the rough place it already has, and whether a storm that size pushes the aurora far enough from the pole to be seen there. If it does, then at night green curtains with violet tops come up behind the far mountains, on a canvas of their own that is left out the rest of the time. They are worked out pixel by pixel on a small canvas twelve times a second and stretched over the sky, which costs about a fifth of a millisecond a frame. Near the edge of where they reach they come out fainter and redder. South of the equator they are the southern lights. Adding ?aurora to the address shows a storm night's lights to anyone.

Leave the world alone for a minute and it dozes off. Leave it a couple of minutes more and it dreams. Each time you hover something new, the renderer copies a small round picture of it out of its own layers, keeping the last eight in memory and nowhere else. Once the world is deep enough asleep, those pictures drift one by one across the high sky, faint as a memory, and they fade the moment you move.

The source is in lib/world (opens in a new tab) if you want to read it.