Interactive 3D Ocean Waves: 2.5D Canvas Heightmap Displacement & Gerstner Wave Physics Guide

The Quick Answer

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.

Interactive Demo Live Preview
🌊 2.5D Gerstner Swell · Move cursor to create wake ripples

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).

gerstner-math.js
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).

perspective-mesh.js
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.

ocean-renderer.js
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:

1. Gerstner Wave Math & Crest Peaking

Multi-harmonic trochoidal wave formula producing authentic physical ocean swells with horizontal crest sharpening and expansive troughs.

2. Dynamic Vertex Lighting & Specular Foam

Calculates local slope gradients and sun vector dot products to render shimmering light glints and foam caps across elevated wave ridges.

3. Interactive Cursor Wake Displacement

Raycast pointer detection that injects dynamic ripple shockwaves and disturbance velocity fields into the water surface mesh.

Chaam
Chaam's Pro Tip

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.

Why I Built the Mesh Gradient Studio

I got tired of guessing values and testing browser quirks in DevTools, so I built this tool to tweak and preview values in real time with 1-click code export.

Open in Mesh Gradient Studio ↗

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.

← Back to all blog guides Launch Generator Studio →