Animated Topographic Contours With Marching Squares
The Island
The sliders change the number of contour levels, how much noise is mixed into the hill, and the size of the grid the contours are traced on. Turn on "Show grid" to see that grid.
The island is a single <canvas>. Nothing here uses WebGL or a library; it is a few hundred lines of plain JavaScript and the Canvas 2D API. Drawing one frame happens in three steps:
- Build a height field: a number for every point on a grid, like the elevation of a piece of land.
- Trace contours through that field with marching squares, at evenly spaced elevations.
- Fill each elevation tier with a slightly darker color than the one below it, then stroke the contour lines on top.
Animation is just doing that again a few times a second while the terrain slowly changes.
The Height Field
The terrain comes from Perlin noise, a function that takes a coordinate and returns a smoothly varying value between roughly -1 and 1. Nearby inputs give nearby outputs, which is what makes it look like rolling land instead of static. The noise function is seeded, so each island gets its own terrain but the same seed always draws the same island.
Plain noise is a bit too smooth and blobby, so two tricks are layered on top of it.
Fractal Brownian motion (fBm) adds several copies of the noise together, each at twice the frequency and half the strength of the last. The first layer sets the big hills, and the later layers add smaller bumps on top of them, the way real terrain has detail at every scale.
export function fbm(noise, x, y, z, octaves = 3) {
let sum = 0;
let amp = 0.5;
let norm = 0;
for (let o = 0; o < octaves; o++) {
sum += amp * noise(x, y, z);
norm += amp;
x *= 2.03; // a hair over 2, so the layers don't line up on a grid
y *= 2.03;
z *= 1.7;
amp *= 0.5;
}
return sum / norm;
}
Domain warping nudges each sample point by another noise field before sampling. Instead of reading the noise at (x, y), we read it at (x, y) plus a small, smoothly varying offset. That bends the straight-ish ridges of the noise into meanders that look a lot more like eroded land.
Noise on its own fills the whole canvas with terrain, though, and I wanted an island: something with a shore. So the noise is added to a dome, a round hill centered in the canvas whose height falls off with the square of the distance from the middle. Finally the whole thing is faded down to sea level before it reaches the edge of the canvas. Without that fade, any contour that reached the edge would get cut off in a straight line.
Here are those pieces with the same seed:
export function islandHeight(noise, x, y, w, h, z, { dome = 0.75, terrain = 0.6 }) {
// Distance from the center, where 1 is the edge of the circle that fits the canvas
const r = Math.min(w, h) / 2;
const dx = (x - w / 2) / r;
const dy = (y - h / 2) / r;
const d = Math.sqrt(dx * dx + dy * dy);
// About 2.4 noise "cells" across the island
const s = 2.4 / r;
const nx = x * s;
const ny = y * s;
// Domain warp: shift the sample point by another noise field
const wx = nx + 0.6 * noise(nx * 0.5, ny * 0.5, z + 3.1);
const wy = ny + 0.6 * noise(nx * 0.5 + 5.2, ny * 0.5, z + 8.4);
const height = (1 - d * d) * dome + fbm(noise, wx, wy, z, 3) * terrain;
// Fade to sea level over the outer part of the circle, with a smoothstep
const e = Math.min(Math.max((0.97 - d) / 0.3, 0), 1);
return e * e * (3 - 2 * e) * height;
}
The "Terrain noise" slider in the demo is the terrain weight. At zero you get the plain dome and perfectly round rings; turn it up and the hills break up into separate peaks and valleys.
The height is not computed for every pixel. It's sampled on a grid, one value every 10 pixels by default (the "Grid cell" slider), and stored in a flat Float32Array. A 400 pixel island is a 41 × 41 grid, which is only about 1,700 samples per frame.
Marching Squares
Now we need to turn that grid of numbers into shapes. Marching squares is the classic way to do it, and it's the same algorithm I used for the contour lines in the 3D terrain post.
Pick one elevation, say 0.4. Every corner of the grid is now either above it or below it. Look at each grid cell one at a time:
- If all four corners are below, the cell is empty.
- If all four are above, the whole cell is inside the shape.
- Otherwise the boundary passes through the cell. Somewhere along each edge that has one corner above and one below, the height crosses exactly 0.4.
We don't know the true height between the corners, so we assume it changes linearly and interpolate to find the crossing point. If one corner is 0.2 and the next is 0.6, the 0.4 crossing is halfway along the edge.
Most explanations of marching squares use a 16-entry lookup table, one entry for each combination of corners above and below. For filled shapes there's a simpler way: walk around the four edges of the cell clockwise, and keep every corner that is above the threshold, plus every crossing point you pass. What you are left with is the polygon of the part of the cell that is above the threshold.
const edge = (xa, ya, va, xb, yb, vb) => {
if (va >= th) pts.push(xa, ya); // keep corners above the threshold
if (va >= th !== vb >= th) { // this edge straddles the threshold
const k = (th - va) / (vb - va); // linear interpolation along the edge
const px = xa + (xb - xa) * k;
const py = ya + (yb - ya) * k;
pts.push(px, py); // part of the filled shape...
cross.push(px, py); // ...and an end of a contour line
}
};
edge(x0, y0, a, x1, y0, b); // top
edge(x1, y0, b, x1, y1, c); // right
edge(x1, y1, c, x0, y1, d); // bottom
edge(x0, y1, d, x0, y0, a); // left
The crossing points also give us the contour line for free. A cell has either two crossings, which get joined by one short line segment, or four, where two diagonal corners are above and the other two below. That's the "saddle" case, which is ambiguous: you can't tell from the corners alone whether the two high corners are connected through the middle of the cell. Here I just pair the crossings in order. At this scale it is impossible to see which way it guessed.
Turn on "Show grid" in the demo and push the grid cell slider up. Every contour is a chain of straight segments, one per cell. At 10 pixels the interpolation makes them look like smooth curves; at 28 you can see the corners.
Filling the Tiers
The color comes from drawing the levels in order from lowest to highest, like stacking a wedding cake. The region above the first level is filled with the palest color, the region above the second level is filled on top of it with a slightly darker one, and so on up to the peak. Each level only has to fill the area above its own threshold, and the levels below show through around it.
Each level's cells all go into a single Path2D and get filled with one call. That matters for more than speed. If each cell were filled separately, the anti-aliased edges of neighboring cells would leave faint seams across the shape. Filled as one path, the shared edges between cells disappear. Cells that are entirely inside the shape are added as plain rectangles, which is most of them.
for (let l = 0; l < levels; l++) {
const fill = new Path2D();
const line = new Path2D();
// ...marching squares over every cell, adding to `fill` and `line`...
ctx.fillStyle = ramp(palette.tiers, l / (levels - 1));
ctx.fill(fill);
lines.push(line);
}
// Lines go on last, so no tier is painted over them
lines.forEach((line, l) => {
const index = l % 4 === 0;
ctx.strokeStyle = index ? palette.indexLine : palette.line;
ctx.lineWidth = index ? 1.25 : 0.75;
ctx.stroke(line);
});
Every fourth line is drawn a little heavier. On a real topographic map these are called index contours: every fifth line is thicker and labeled with its elevation, so you can count your way up a slope without losing your place. Here it just gives the eye a rhythm.
The colors are deliberately pale. The light theme runs from an off-white close to the page color up to a soft sage, and the lines are a brown at 18% opacity. Switch the site to dark mode and the palette swaps to dark olive tones with light lines.
Animating It
The noise is three-dimensional, but the map is flat. The third dimension is time. Each frame samples the same (x, y) grid at a slightly larger z, and because the noise is continuous in all three directions, the terrain doesn't jump between frames. It morphs. Hills rise and sink, ridges slide around, and new peaks bubble up out of the valleys.
const z = elapsedSeconds * 0.02;
That 0.02 keeps it slow enough that you only notice the change if you watch the island for a few seconds.
A few things keep the cost down:
- Throttled frame rate. The terrain moves so slowly that 20 frames a second looks identical to 60, so the
requestAnimationFrameloop skips frames until enough time has passed. - Only animate what's visible. Each island has an
IntersectionObserver, and its loop only runs while it is on screen. Scroll this page and the islands you can't see stop drawing. - Capped pixel ratio. The canvas is sized to its box times
devicePixelRatio, capped at 2. AResizeObserverresizes it and redraws whenever its box changes. - Reduced motion. If the visitor has asked their operating system for reduced motion, each island draws one still frame and stops.