Interactive 3D Ocean Waves: 2.5D Canvas Heightmap Displacement & Gerstner Wave Physics Guide
Simulating 3D ocean waves in 2D HTML5 Canvas is accomplished by projecting a 2.5D isometric vertex grid into screen space using perspective division (Z-depth). Each vertex displacement is governed by superimposed Gerstner wave equations which produce sharp crests and broad troughs, paired with normal-vector dot product lighting to calculate foam highlights and cursor boat wakes at 60 FPS.
Step 1: Gerstner Wave Trigonometric Displacement Physics
Unlike simple sine waves which produce unnatural rounded peaks, real deep-water oceanic swell forms sharp trochoidal crests and wide troughs. The Gerstner wave equation displaces vertices horizontally toward the wave crest while elevating them vertically: x = x₀ - (k_x/k)·A·sin(k·x₀ - ωt), y = y₀ - (k_y/k)·A·sin(k·y₀ - ωt), z = A·cos(k·x₀ - ωt).
class GerstnerWave {
constructor(direction, steepness, wavelength) {
this.dir = direction; // [dx, dy] normalized
this.w = Math.sqrt(9.8 * ((2 * Math.PI) / wavelength)); // angular frequency
this.k = (2 * Math.PI) / wavelength; // wave number
this.a = steepness / this.k; // amplitude
}
evaluate(x, y, time) {
const dot = this.dir[0] * x + this.dir[1] * y;
const phase = this.k * dot - this.w * time;
const cosP = Math.cos(phase);
const sinP = Math.sin(phase);
return {
dx: -(this.dir[0] * this.a * sinP),
dy: -(this.dir[1] * this.a * sinP),
dz: this.a * cosP
};
}
}
Step 2: Projecting 2.5D Grid Mesh into Canvas Screen Space
We arrange vertices in a regular row/column plane tilted backwards in 3D space with an isometric pitch angle. Each world coordinate (X, Y, Z) is projected onto the 2D canvas using perspective scaling factor: scale = fov / (fov + Z_depth).
function projectVertex(worldX, worldY, worldZ, fov, camY, camZ, cx, cy) {
const rotAngle = 0.55; // Pitch tilt forward
// Rotate around X-axis
const ry = worldY * Math.cos(rotAngle) - worldZ * Math.sin(rotAngle) + camY;
const rz = worldY * Math.sin(rotAngle) + worldZ * Math.cos(rotAngle) + camZ;
if (rz <= 0.1) return null; // Behind camera plane
const scale = fov / rz;
return {
screenX: cx + worldX * scale,
screenY: cy + ry * scale,
depth: rz,
elevation: worldZ
};
}
Step 3: Rendering Shaded Polygonal Strips with Specular Crest Highlights
We traverse the mesh from furthest back to front (painter's algorithm). Quad faces are drawn with depth-based atmospheric fog and specular lighting calculated from surface height differentials to simulate sun glare and ocean crest foam.
function renderOceanMesh(ctx, grid, width, height) {
for (let z = 0; z < grid.rows - 1; z++) {
for (let x = 0; x < grid.cols - 1; x++) {
const p1 = grid.get(x, z);
const p2 = grid.get(x + 1, z);
const p3 = grid.get(x + 1, z + 1);
const p4 = grid.get(x, z + 1);
if (!p1 || !p2 || !p3 || !p4) continue;
// Color interpolation: deep ocean navy to turquoise crest foam
const avgElev = (p1.elevation + p2.elevation + p3.elevation + p4.elevation) * 0.25;
const foamRatio = Math.max(0, Math.min(1, (avgElev + 15) / 35));
ctx.beginPath();
ctx.moveTo(p1.screenX, p1.screenY);
ctx.lineTo(p2.screenX, p2.screenY);
ctx.lineTo(p3.screenX, p3.screenY);
ctx.lineTo(p4.screenX, p4.screenY);
ctx.closePath();
const r = Math.floor(10 + foamRatio * 40);
const g = Math.floor(40 + foamRatio * 180);
const b = Math.floor(90 + foamRatio * 155);
ctx.fillStyle = `rgba(${r}, ${g}, ${b}, 0.85)`;
ctx.strokeStyle = `rgba(255, 255, 255, ${foamRatio * 0.4})`;
ctx.lineWidth = 0.5;
ctx.fill();
ctx.stroke();
}
}
}
Next-Level Addons: Elevating Your Implementation
Take this technique further by combining it with complementary design token studios and animation tools:
When building high-performance UI animations or particle systems, my golden rule is: never calculate layout triggers (like getBoundingClientRect() or offsetHeight) inside animation loops. Read measurements once upfront and use CSS transforms or Canvas for buttery 60fps.
Frequently Asked Questions
Practical answers to common implementation questions, browser quirks, and performance tips.
Why are Gerstner waves preferred over standard sinusoidal sine waves for water?
Standard sinusoidal waves create symmetric rounded peaks and valleys. In natural oceans, gravity and surface tension pull water particles in circular orbital motions, causing wave crests to pinch sharply into narrow ridges while troughs flatten out broadly. Gerstner waves mathematically replicate this trochoidal motion by displacing vertices horizontally as well as vertically.
How do you prevent perspective sorting artifacts without WebGL depth buffers?
In 2D Canvas, we sort vertices or polygonal quad rows strictly from back to front using the classic painter's algorithm. Because the ocean plane is structured as a regular isometric grid tilted forward, iterating row-by-row from the furthest distance (Z-max) to the nearest foreground (Z-min) guarantees perfect occlusion without requiring a 3D Z-buffer.
How is wave foam generated along the wave crests?
Foam is calculated through height thresholding and Jacobian determinant evaluation. When wave height exceeds a normalized elevation threshold (e.g. 75% peak height) or when horizontal vertex displacement converges (indicating a breaking crest), we interpolate the polygon stroke and fill colors toward high-contrast white and cyan.
Can the camera position and viewing angle be adjusted interactively?
Yes. By storing camera pitch, yaw, and elevation in an orientation matrix, mouse drag or device orientation events can rotate the projection coordinate frame, allowing users to inspect the ocean mesh from high-altitude bird's eye perspectives down to water-level skimming horizons.
What is the performance overhead on mobile devices?
A 2.5D ocean mesh with 30 columns by 30 rows contains only 900 vertices and 841 quads. Modern mobile mobile Safari and Chromium browsers execute these 900 trigonometric evaluations and Canvas polygon fills in less than 4ms per frame, ensuring smooth 60 FPS performance without draining mobile battery.