Generative Topographic Elevation Contours: HTML5 Canvas, Marching Squares & Simplex Noise Guide
Generating real-time topographic contours on HTML5 Canvas is accomplished by sampling a continuous 2D Simplex or Perlin noise heightmap into a coarse scalar grid, then extracting isolines at discrete elevation thresholds using the Marching Squares lookup table. Linear interpolation between grid cell vertices ensures smooth curves, while stroke styling with alpha falloffs and cursor elevation slicing brings interactive terrain maps to life at 60 FPS.
Step 1: Sampling the 2D Continuous Noise Scalar Grid
Rather than recalculating noise for every single screen pixel, we evaluate a continuous Simplex noise heightmap over a discrete 2D scalar grid (e.g. 10px or 16px cell stride). Each grid vertex stores a normalized elevation value between 0.0 and 1.0, optionally perturbed over time by an animated time offset.
class ElevationGrid {
constructor(width, height, cellSize) {
this.cols = Math.ceil(width / cellSize) + 1;
this.rows = Math.ceil(height / cellSize) + 1;
this.cellSize = cellSize;
this.grid = new Float32Array(this.cols * this.rows);
}
sample(noiseFn, time = 0, scale = 0.005) {
for (let r = 0; r < this.rows; r++) {
for (let c = 0; c < this.cols; c++) {
const nx = c * this.cellSize * scale;
const ny = r * this.cellSize * scale;
// Sample multi-octave fractal brownian motion
const elev = (noiseFn(nx, ny, time) + 1) * 0.5;
this.grid[r * this.cols + c] = elev;
}
}
}
get(c, r) {
return this.grid[r * this.cols + c];
}
}
Step 2: Marching Squares Isoline Extraction with Vertex Interpolation
For any chosen elevation threshold (isolevel), every square grid cell is classified into one of 16 binary topological configurations based on whether its 4 corners sit above or below the threshold. We compute exact crossing points along the 4 edges via linear interpolation (lerp) to produce organic, non-blocky contour vectors.
function interpolateEdge(p1, p2, val1, val2, iso) {
const mu = (iso - val1) / (val2 - val1);
return {
x: p1.x + mu * (p2.x - p1.x),
y: p1.y + mu * (p2.y - p1.y)
};
}
function traceCellIsoLines(ctx, x0, y0, sz, vTL, vTR, vBR, vBL, iso) {
let mask = 0;
if (vTL >= iso) mask |= 8;
if (vTR >= iso) mask |= 4;
if (vBR >= iso) mask |= 2;
if (vBL >= iso) mask |= 1;
if (mask === 0 || mask === 15) return; // Entirely above or below
const top = interpolateEdge({x: x0, y: y0}, {x: x0 + sz, y: y0}, vTL, vTR, iso);
const right = interpolateEdge({x: x0 + sz, y: y0}, {x: x0 + sz, y: y0 + sz}, vTR, vBR, iso);
const bottom = interpolateEdge({x: x0, y: y0 + sz}, {x: x0 + sz, y: y0 + sz}, vBL, vBR, iso);
const left = interpolateEdge({x: x0, y: y0}, {x: x0, y: y0 + sz}, vTL, vBL, iso);
ctx.beginPath();
switch (mask) {
case 1: case 14: ctx.moveTo(left.x, left.y); ctx.lineTo(bottom.x, bottom.y); break;
case 2: case 13: ctx.moveTo(bottom.x, bottom.y); ctx.lineTo(right.x, right.y); break;
case 3: case 12: ctx.moveTo(left.x, left.y); ctx.lineTo(right.x, right.y); break;
case 4: case 11: ctx.moveTo(top.x, top.y); ctx.lineTo(right.x, right.y); break;
case 6: case 9: ctx.moveTo(top.x, top.y); ctx.lineTo(bottom.x, bottom.y); break;
case 7: case 8: ctx.moveTo(top.x, top.y); ctx.lineTo(left.x, left.y); break;
// Saddles handled by diagonal segment pairs
case 5:
ctx.moveTo(left.x, left.y); ctx.lineTo(top.x, top.y);
ctx.moveTo(bottom.x, bottom.y); ctx.lineTo(right.x, right.y);
break;
case 10:
ctx.moveTo(top.x, top.y); ctx.lineTo(right.x, right.y);
ctx.moveTo(left.x, left.y); ctx.lineTo(bottom.x, bottom.y);
break;
}
ctx.stroke();
}
Step 3: Rendering Layered Isobar Steppes and Interactive Elevation Slicing
We iterate through 12 to 24 elevation thresholds. Major contour lines (every 5th step) are rendered with thicker line weights and higher contrast, while minor contours maintain subtle transparency. We bind mouse coordinates to dynamically highlight the specific contour band currently under the cursor.
function renderContours(ctx, grid, levels, mouseElev) {
const sz = grid.cellSize;
levels.forEach((iso, idx) => {
const isMajor = idx % 5 === 0;
const isHovered = Math.abs(iso - mouseElev) < 0.04;
ctx.lineWidth = isHovered ? 2.5 : (isMajor ? 1.5 : 0.8);
ctx.strokeStyle = isHovered
? '#38bdf8'
: (isMajor ? 'rgba(56, 189, 248, 0.75)' : 'rgba(56, 189, 248, 0.25)');
for (let r = 0; r < grid.rows - 1; r++) {
for (let c = 0; c < grid.cols - 1; c++) {
traceCellIsoLines(
ctx, c * sz, r * sz, sz,
grid.get(c, r), grid.get(c + 1, r),
grid.get(c + 1, r + 1), grid.get(c, r + 1),
iso
);
}
}
});
}
Next-Level Addons: Elevating Your Implementation
Take this technique further by combining it with complementary design token studios and animation tools:
Here's my golden rule when implementing this in production: test across multiple devices and browsers early. Keep your DOM hierarchy shallow, optimize assets with modern formats (like WebP/AVIF), and verify keyboard navigation for accessibility.
Frequently Asked Questions
Practical answers to common implementation questions, browser quirks, and performance tips.
What is the Marching Squares algorithm and why is it used for topographic contours?
Marching Squares is a computer graphics algorithm that generates 2D contour lines (isolines) from a grid of scalar elevation values. By evaluating the corners of each square cell against a threshold value, it determines whether lines pass through the cell and connects boundary edges with smooth linear interpolation, producing realistic geographic isobar lines without pixelated stepping.
How does Simplex Noise differ from Perlin Noise for topographic generation?
Simplex noise scales with O(n²) computational complexity compared to classic Perlin noise O(2ⁿ), yielding 30% to 50% faster calculation times in 2D and 3D. Furthermore, Simplex noise does not suffer from visible directional grid artifacts or square directional bias, making continuous topographic ridges look organic and geologically authentic.
What resolution should the scalar grid be for optimal 60 FPS performance?
A grid cell size of 12px to 20px strikes the ideal balance between rendering performance and visual fidelity. Sampling a 1920x1080 screen at 16px yields approximately 120x68 = 8,160 sample points, which standard JavaScript engines evaluate in under 3 milliseconds per frame, leaving ample GPU time for 60 FPS Canvas stroke rendering.
Can Marching Squares topographic contours be exported as vector SVG paths?
Yes. Because Marching Squares produces discrete coordinate segment pairs (x1, y1) to (x2, y2), these segments can either be connected into closed vector polylines using a path stitcher graph or drawn directly into SVG path strings (M x1 y1 L x2 y2) for infinite-resolution vector print outputs.
How do you handle ambiguous saddle points in Marching Squares?
When diagonally opposing corners are high and the other two are low (cases 5 and 10), an ambiguous saddle occurs. To resolve topological connectivity correctly without crossing lines, you sample the average center value of the 4 cell vertices: if the center is above the isolevel, connect the corners one way; otherwise, connect them the other way.