Bathymetry maps in Three.js
A bathymetry grid stores the height of the seabed at regular intervals. Turn those samples into a Three.js mesh and you can see where a shelf drops into a channel, switch to a top-down map and click the bottom to read its depth.
Prepare the depth data
Start with a small, regularly spaced grid in metres. Use local eastings for X and southings for Z, with Y pointing up. If your raster is in latitude and longitude, reproject it to a suitable local metric coordinate system before measuring distances. When reading a projected raster, get the placement of the sample centres and the grid spacing from its metadata.
Check the vertical datum and sign when you load the file. The GEBCO grid stores seabed elevations as negative values in metres. This example uses positive depth measured down from a flat reference at waterY = 0, so a depth of 12 m becomes y = -12. If you already have elevations relative to the scene’s datum, put those directly on Y. GEBCO grid format and datum
Decode the raster’s NoData value or validity mask before processing heights. The demo stores missing samples as null and drops any triangle that touches one. A zero depth still means the bed is right at the reference level.
Build the mesh
Put one vertex at each sample centre. Connect neighbouring centres into an indexed grid with two triangles per complete cell. Store each vertex’s colour in a second buffer and turn on vertexColors in the material. The example uses MeshBasicMaterial so changing the camera doesn’t change the depth colours. Three.js BufferGeometry manual
Give the legend fixed steps in metres so the same colour has the same meaning in plan and relief views. For the contours, interpolate where each triangle crosses 10, 20 and 30 m, then draw a line between the two crossings.
Try the depth map
Select Plan view and tap the channel to read an interpolated depth. Focus the map and use the arrow keys to inspect the original grid samples. Try tapping the empty patch near the eastern edge. Open the bathymetry example
Save this block as index.html and run python3 -m http.server 8080 from the same folder. The example imports Three.js r184 and generates its own depth samples.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,follow">
<title>Three.js bathymetry map demo</title>
<link rel="icon" href="data:,">
<style>
* { box-sizing: border-box; }
body { margin: 0; background: #f4f4f0; color: #1a1a18; font: 1rem/1.45 system-ui, sans-serif; }
main { max-width: 72rem; margin: auto; padding: clamp(1rem, 3vw, 2rem); }
header, footer { display: flex; justify-content: space-between; align-items: end; gap: .8rem 2rem; flex-wrap: wrap; }
h1 { margin: 0; font-size: clamp(1.7rem, 3.6vw, 2.7rem); font-weight: 500; line-height: 1.1; }
p, output { margin: .4rem 0 0; }
#plot { min-height: 15rem; height: min(55vh, 78vw, 38rem); margin: 1rem 0; border: 1px solid #d2d7d5; }
canvas { display: block; cursor: crosshair; width: 100%; height: 100%; }
button { min-height: 44px; padding: .5rem .9rem; border: 1px solid #676762; border-radius: 8px;
background: #fff; color: inherit; font: inherit; cursor: pointer; }
#legend { width: min(60vw, 14rem); display: flex; text-align: center; font-variant-numeric: tabular-nums; }
#legend span { flex: 1; border-top: .6rem solid var(--swatch); padding-top: .15rem; }
#selection { display: block; font-size: 1.15rem; font-variant-numeric: tabular-nums; }
#instructions { font-size: .9rem; color: #565954; }
:focus-visible { outline: 2px solid #1a1a18; outline-offset: 3px; }
</style>
</head>
<body>
<main>
<header>
<div><h1>Bathymetry map</h1><p>Synthetic seabed sampled every 5 m</p></div>
<button id="view" type="button" aria-pressed="false" disabled>Plan view</button>
</header>
<div id="plot"></div>
<footer>
<div>
<output id="selection" aria-live="polite">Loading depth map…</output>
<p id="instructions">Tap the seabed or focus the map and use the arrow keys.</p>
</div>
<div>
<div id="legend-label">Water depth (m)</div>
<div id="legend" role="group" aria-labelledby="legend-label"></div>
</div>
</footer>
<noscript>Enable JavaScript to inspect the map.</noscript>
</main>
<script type="module">
import * as THREE from "https://cdn.jsdelivr.net/npm/three@0.184.0/build/three.module.js";
const columns = 33;
const rows = 25;
const spacing = 5; // metres between sample centres
const waterY = 0;
const stops = [0xe6e2b9, 0x78c4b7, 0x3786a0, 0x245574, 0x193450];
const stopDepths = [0, 10, 20, 30, 40];
const ramp = stops.map(value => new THREE.Color(value));
const plot = document.querySelector("#plot");
const selection = document.querySelector("#selection");
const button = document.querySelector("#view");
const legend = document.querySelector("#legend");
for (const [i, depth] of stopDepths.entries()) {
const swatch = document.createElement("span");
swatch.textContent = depth;
swatch.style.setProperty("--swatch", "#" + ramp[i].getHexString());
legend.append(swatch);
}
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
const canvas = renderer.domElement;
canvas.tabIndex = 0;
canvas.setAttribute("role", "img");
canvas.setAttribute("aria-label", "Seabed depth map");
canvas.setAttribute("aria-describedby", "instructions");
plot.append(canvas);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8edeb);
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 650);
const samples = [];
const positions = [];
const colors = [];
const indices = [];
const color = new THREE.Color();
function sampleDepth(x, z) {
// A shallow shelf falls away into a curved channel.
const centre = 65 + 24 * Math.sin((z - 45) / 38);
const distance = (x - centre) / 29;
const channel = 32 * Math.exp(-(distance ** 2));
const shelf = 2.5 + 4 * z / 120 + 1.1 * Math.cos(x * 0.085 + z * 0.058);
return Math.round(Math.min(40, channel + shelf));
}
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
const x = column * spacing;
const z = row * spacing;
// Use null after decoding the source raster's NoData value.
const gap = column >= 25 && column <= 28 && row >= 7 && row <= 10;
const depth = gap ? null : sampleDepth(x, z);
samples.push(depth);
// A placeholder keeps array indices aligned. No triangle uses it.
positions.push(x, waterY - (depth ?? 0), z);
const t = THREE.MathUtils.clamp((depth ?? 0) / 10, 0, 4);
const i = Math.min(Math.floor(t), 3);
color.copy(ramp[i]).lerp(ramp[i + 1], t - i);
colors.push(color.r, color.g, color.b);
}
}
function addTriangle(a, b, c) {
if (samples[a] !== null && samples[b] !== null && samples[c] !== null) {
indices.push(a, b, c);
}
}
for (let row = 0; row < rows - 1; row++) {
for (let column = 0; column < columns - 1; column++) {
const a = row * columns + column;
const b = a + 1;
const c = a + columns;
const d = c + 1;
addTriangle(a, c, b);
addTriangle(b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.setIndex(indices);
const seabed = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ vertexColors: true }));
scene.add(seabed);
// Trace where each triangle crosses the labeled depth intervals.
const contours = [];
for (const level of [10, 20, 30]) {
for (let face = 0; face < indices.length; face += 3) {
for (let edge = 0; edge < 3; edge++) {
const a = indices[face + edge];
const b = indices[face + (edge + 1) % 3];
if ((samples[a] < level) === (samples[b] < level)) continue;
const t = (level - samples[a]) / (samples[b] - samples[a]);
contours.push(
THREE.MathUtils.lerp(positions[a * 3], positions[b * 3], t),
waterY - level + 0.1,
THREE.MathUtils.lerp(positions[a * 3 + 2], positions[b * 3 + 2], t)
);
}
}
}
const lines = new THREE.BufferGeometry();
lines.setAttribute("position", new THREE.Float32BufferAttribute(contours, 3));
scene.add(new THREE.LineSegments(lines, new THREE.LineBasicMaterial({
color: 0xffffff, transparent: true, opacity: 0.35, depthWrite: false
})));
const marker = new THREE.Mesh(
new THREE.SphereGeometry(2, 16, 10), new THREE.MeshBasicMaterial({ color: 0xffdf88 })
);
scene.add(marker);
const ray = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let row = 12;
let column = 16;
function draw() {
renderer.render(scene, camera);
}
function showPoint(x, z, depth, sample) {
marker.visible = depth !== null;
if (marker.visible) marker.position.set(x, waterY - depth + 1.5, z);
const place = `East ${Math.round(x)} m · South ${Math.round(z)} m`;
selection.value = depth === null ? `No depth sample · ${place}` :
`${Math.round(depth)} m depth · ${place}${sample ? "" : " · interpolated"}`;
draw();
}
function showSample() {
showPoint(column * spacing, row * spacing, samples[row * columns + column], true);
}
function setView() {
const plan = button.getAttribute("aria-pressed") === "true";
if (plan) {
camera.position.set(80, 200, 60);
camera.up.set(0, 0, -1); // north is up on the plan
camera.lookAt(80, 0, 60);
} else {
camera.position.set(210, 160, 205);
camera.up.set(0, 1, 0);
camera.lookAt(80, -8, 60);
}
fit();
}
function fit() {
const width = plot.clientWidth;
const height = plot.clientHeight;
const aspect = width / height;
const halfHeight = Math.max(70, 104 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
draw();
}
button.addEventListener("click", () => {
button.setAttribute("aria-pressed", button.getAttribute("aria-pressed") !== "true");
setView();
});
canvas.addEventListener("click", event => {
const rect = canvas.getBoundingClientRect();
pointer.set(2 * (event.clientX - rect.left) / rect.width - 1,
1 - 2 * (event.clientY - rect.top) / rect.height);
ray.setFromCamera(pointer, camera);
const hit = ray.intersectObject(seabed, false)[0];
if (!hit) {
marker.visible = false;
selection.value = "No depth data at this point";
draw();
return;
}
const { x, y, z } = seabed.worldToLocal(hit.point);
column = THREE.MathUtils.clamp(Math.round(x / spacing), 0, columns - 1);
row = THREE.MathUtils.clamp(Math.round(z / spacing), 0, rows - 1);
showPoint(x, z, waterY - y, false);
});
canvas.addEventListener("keydown", event => {
switch (event.key) {
case "ArrowUp": row = Math.max(0, row - 1); break;
case "ArrowDown": row = Math.min(rows - 1, row + 1); break;
case "ArrowLeft": column = Math.max(0, column - 1); break;
case "ArrowRight": column = Math.min(columns - 1, column + 1); break;
default: return;
}
event.preventDefault();
showSample();
});
button.disabled = false;
setView();
showSample();
new ResizeObserver(fit).observe(plot);
</script>
</body>
</html>
Read a depth
Raycaster returns a hit on one of the triangles between samples. Convert its hit point to mesh-local coordinates, then subtract its Y value from the reference level. This gives the depth at that point on the rendered mesh. Arrow keys step along whole rows and columns and read the stored depth directly. Three.js Raycaster reference
The example reports whole metres, matching the sample values. A finer mesh can make a view look smoother without adding survey detail. When you label a real dataset, use its documented resolution and accuracy to set the display precision.
Add the water surface
Keep the bed fixed in its own datum when the tide changes. Move the rendered water to the new elevation, then calculate the current depth as waterElevation - bedElevation. Use a colour map for the explanatory view and a separate water material for the view that needs reflections and shoaling waves. Read the water level from a tide gauge · Drive surf with a signed depth field