Three.js Scroll Coral Reef Grow — Reef Restoration Story
Three.js Scroll Coral Reef Grow · Scroll · Plain HTML, CSS & JS · Live preview
About this UI Snippet
Three.js Scroll Coral Reef Grow — A Reef That Comes Back to Life as You Scroll

This snippet tells a small restoration story underwater. It opens on a sandy seabed 12 metres down with rocks, drifting marine snow, light rays from the surface and bright caustic patterns rippling across the sand. All that is left of the reef is bleached white stumps. As you scroll, the coral grows back and its colour returns colony by colony: bushy staghorn coral, flat sea fans, clusters of tube anemones and round brain corals. Halfway through, the fish start coming back in four schools, bubbles rise from the reef, and the camera circles down into it. A HUD tracks reef health and the number of fish, and four chapter captions narrate the recovery. Scroll back up and it all fades again.
One scroll value, many timelines
A GSAP tween on a pinned ScrollTrigger (scrub: 1, 450% of scroll) takes form.t from 0 to 1. Everything else is worked out from that number every frame: each coral segment has its own start and end time, each colony has a time when its colour comes back, each fish has a time when it appears, and the camera path is a function of it. Separately, a running time value drives the things that should keep moving when you stop scrolling: the swaying coral, the swimming fish, the bubbles and the caustics.
Coral built from branches
Staghorn and sea fans are generated by a small recursive branch() function. Each call adds one segment, then spawns two or three children from its tip with a shorter length, a thinner radius and a turned direction, down to four levels. Sea fans only turn around the fan's own normal, so all their branches stay in one flat plane. Tube anemones are single segments in tight clusters. Every segment remembers a start and end time, and a child starts when its parent is three quarters grown, so the coral visibly spreads outward generation by generation. Staghorn trunks start at 40% length, which is what makes the bleached stumps.
About 1,700 pieces, four draw calls
All branch segments share one tapered cylinder in a THREE.InstancedMesh, the rounded tips share one sphere, the brain corals share one bumpy icosahedron (vertices pushed out by a product of sines), and the fish share one hand-built low-poly fish geometry. Each frame the script writes a matrix per instance: position at the middle of the segment, rotation from setFromUnitVectors, and scale for radius and current length. Instances that have not started yet get a zero-scale matrix.
Swaying that keeps branches joined
The water movement is a function of position only: sway(p) returns a small sideways offset that grows with height and changes over time. Both ends of every segment are pushed by it, and because a child segment starts exactly where its parent ends, connected branches bend together instead of coming apart. Sea fans sway a bit more and anemones a lot more, set by a per-colony amplitude.
Colour coming back
Each colony has a living colour, and its instances are blended from a bleached off-white to that colour as the scroll passes the colony's start time, with tips a little lighter. Instance colours are only rewritten when the scroll value has actually changed, which keeps the per-frame cost down.
Water you can feel
The caustics are a Voronoi texture made on a canvas: pixels where the distance to the nearest and second-nearest point is almost the same light up, which gives the familiar net of light lines. The points wrap around, so it tiles, and it is used as the seabed's emissive map and slowly scrolled. The light rays are additive planes with a soft canvas gradient that always turn to face the camera. Fog matches the water colour so the reef fades into blue in the distance.
Fish schools
Each school circles the reef at its own radius, height and speed. Fish keep a random offset inside the school that rotates with it, so the formation turns as one, plus a small wobble. Their heading comes from the circle's tangent. The schools appear one after another from 50% to 80% of the scroll, a fish at a time. The Three.js Scroll Jellyfish Drift and Three.js Scroll Galaxy Formation snippets use the same scroll-to-world approach.
What's included
Features
Step by step
How to Use
- 1Load the three CDN scriptsAdd three.min.js, gsap.min.js and ScrollTrigger.min.js from the CDN panel, in that order, before the snippet JS.
- 2Scroll through the reefThe stage pins. Bleached stumps grow back and colour returns, sea fans and anemones spread, then fish schools arrive while the camera circles down.
- 3Stop scrollingThe coral keeps swaying, the fish keep swimming and the light keeps rippling. Scroll back up to watch the reef fade again.
- 4Change the reefEdit the colony loops: the number of staghorn, fan and anemone colonies, their colour lists, start times and branch depth.
- 5Change the fishEdit the SCHOOLS array: colour, number of fish, circle radius, height, speed, size and the scroll point (th) where each school arrives.
- 6Tune the waterChange the fog colour and distances, the caustics emissiveIntensity, or the number of light rays and bubbles.
Real-world uses
Common Use Cases
Got questions?
Frequently Asked Questions
A recursive branch() function adds a segment, then spawns two or three children from its tip with a shorter length, a thinner radius and a turned direction, four levels deep. Sea fans only turn around their own normal so they stay flat. Each segment stores a start and end time, and children start when their parent is three quarters grown, which makes the coral spread outward as you scroll.
All branch segments are instances of one cylinder, all tips of one sphere, all brain corals of one bumpy sphere and all fish of one small fish geometry, so the reef is four draw calls. Each frame the script only writes a transform matrix per instance, and instance colours are rewritten only when the scroll position changes.
The sway offset is a function of position (and time) only. Both ends of every segment are moved by it, and a child segment starts at exactly the point where its parent ends, so the two ends get the same offset and the joint never opens up.
A 256 px canvas is filled with a Voronoi pattern: for each pixel the distances to the nearest and second-nearest of 24 random points are compared, and pixels where they are almost equal are bright. The points wrap around the edges, so the texture tiles. It is used as the seabed's emissive map and its offset drifts over time.
Yes. Click JSX for a React component, Vue for a Vue 3 SFC or Angular for a standalone component. Build the scene in a mount effect against a canvas ref, and on unmount kill the ScrollTrigger, cancel the animation frame, disconnect the IntersectionObserver and dispose of the geometries, materials, textures and renderer.
Copy & paste
Source Code
<section class="crf-stage" id="crfStage">
<canvas id="crfCanvas" aria-hidden="true"></canvas>
<div class="crf-vignette"></div>
<div class="crf-intro" id="crfIntro">
<p class="crf-kicker">Reef restoration · 12 m deep</p>
<h2>Bring the reef back</h2>
<p class="crf-hint"><span></span>Scroll to grow the coral</p>
</div>
<div class="crf-chapters">
<p class="crf-ch"><b>01</b>Bare rock<span>Bleached stumps on an empty seabed</span></p>
<p class="crf-ch"><b>02</b>First polyps<span>Colour creeps back into the coral</span></p>
<p class="crf-ch"><b>03</b>Branching out<span>Staghorn, sea fans and anemones spread</span></p>
<p class="crf-ch"><b>04</b>Life returns<span>The fish move back in</span></p>
</div>
<div class="crf-hud">
<div><small>Reef health</small><strong id="crfPct">0</strong><em>%</em></div>
<div><small>Fish</small><strong id="crfFish">0</strong></div>
<div class="crf-bar"><i id="crfBar"></i></div>
</div>
</section>
<section class="crf-after">
<h2>A living reef.</h2>
<p>Scroll back up to watch it fade again: the fish leave, the colour drains and the coral shrinks back to bleached stumps.</p>
</section>*{box-sizing:border-box;margin:0;padding:0}
html,body{background:#031a27;color:#eafcff;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}
.crf-stage{position:relative;height:100vh;height:100dvh;overflow:hidden;background:linear-gradient(#0f6a8c 0%,#0a4560 38%,#052638 75%,#031a27 100%)}
#crfCanvas{display:block;width:100%;height:100%}
.crf-vignette{position:absolute;inset:0;pointer-events:none;background:radial-gradient(ellipse at 50% 45%,transparent 50%,rgba(1,12,20,.7) 100%)}
.crf-intro{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;text-align:center;padding:24px;pointer-events:none;transition:opacity .5s ease,transform .5s ease}
.crf-intro.is-hidden{opacity:0;transform:translateY(-14px)}
.crf-kicker{font-size:12px;font-weight:700;letter-spacing:.26em;text-transform:uppercase;color:#7ee0f5}
.crf-intro h2{font-size:clamp(36px,6vw,74px);font-weight:800;letter-spacing:-.03em;line-height:1;text-shadow:0 4px 30px rgba(0,20,30,.6)}
.crf-hint{display:flex;flex-direction:column;align-items:center;gap:10px;margin-top:8px;font-size:12px;letter-spacing:.2em;text-transform:uppercase;color:#a7dbe8}
.crf-hint span{width:1px;height:36px;background:linear-gradient(#7ee0f5,transparent);transform-origin:top;animation:crfDrip 1.8s ease-in-out infinite}
@keyframes crfDrip{0%{transform:scaleY(0);opacity:1}60%{transform:scaleY(1);opacity:1}100%{opacity:0}}
.crf-chapters{position:absolute;left:clamp(20px,4vw,48px);top:clamp(20px,6vh,56px);pointer-events:none}
.crf-ch{position:absolute;left:0;top:0;white-space:nowrap;font-size:clamp(22px,2.8vw,32px);font-weight:700;letter-spacing:-.01em;opacity:0;transform:translateY(10px);transition:opacity .5s ease,transform .5s ease;text-shadow:0 2px 18px rgba(0,20,30,.7)}
.crf-ch.is-on{opacity:1;transform:none}
.crf-ch b{display:block;font-size:12px;letter-spacing:.24em;color:#ffb08a;margin-bottom:8px}
.crf-ch span{display:block;font-size:14px;font-weight:400;letter-spacing:0;color:#a7dbe8;margin-top:6px}
.crf-hud{position:absolute;left:clamp(16px,4vw,48px);bottom:clamp(16px,4vh,40px);display:flex;gap:26px;align-items:flex-end;padding:12px 18px 18px;
border:1px solid rgba(126,224,245,.28);border-radius:12px;background:rgba(3,26,39,.5);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);font-variant-numeric:tabular-nums}
.crf-hud small{display:block;font-size:10px;letter-spacing:.2em;text-transform:uppercase;color:#7fb3c2;margin-bottom:2px}
.crf-hud strong{font-size:24px;font-weight:700;color:#ffb08a}
.crf-hud em{font-style:normal;font-size:12px;color:#a7dbe8;margin-left:2px}
.crf-bar{position:absolute;left:18px;right:18px;bottom:8px;height:2px;border-radius:2px;background:rgba(255,255,255,.12);overflow:hidden}
.crf-bar i{display:block;height:100%;background:linear-gradient(90deg,#7ee0f5,#ffb08a);transform:scaleX(0);transform-origin:left}
.crf-after{min-height:70vh;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:12px;text-align:center;padding:48px 24px;background:#031a27}
.crf-after h2{font-size:clamp(26px,3.4vw,40px);letter-spacing:-.02em}
.crf-after p{max-width:480px;color:#8fbccb;font-size:15.5px;line-height:1.7}
@media (max-width:600px){.crf-hud{gap:18px}.crf-hud strong{font-size:20px}.crf-ch span{white-space:normal;max-width:70vw}}
@media (prefers-reduced-motion:reduce){.crf-hint span{animation:none}.crf-intro,.crf-ch{transition:none}}const stage = document.getElementById('crfStage');
const canvas = document.getElementById('crfCanvas');
const pctEl = document.getElementById('crfPct');
const fishEl = document.getElementById('crfFish');
const barEl = document.getElementById('crfBar');
const introEl = document.getElementById('crfIntro');
const chapters = Array.from(document.querySelectorAll('.crf-ch'));
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// Seeded random so the reef looks the same on every load.
let seed = 11;
function rand() {
seed = (seed + 0x6D2B79F5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const pick = arr => arr[Math.floor(rand() * arr.length)];
const clamp01 = v => Math.max(0, Math.min(1, v));
const smooth = (a, b, v) => { const x = clamp01((v - a) / (b - a)); return x * x * (3 - 2 * x); };
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x000000, 0);
const WATER = 0x0a4560;
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(WATER, 6, 58);
const camera = new THREE.PerspectiveCamera(50, 1, 0.1, 200);
scene.add(new THREE.HemisphereLight(0x9be7ff, 0x3b3020, 0.7));
scene.add(new THREE.AmbientLight(0x406070, 0.3));
const sun = new THREE.DirectionalLight(0xdff6ff, 0.9);
sun.position.set(5, 20, 6);
scene.add(sun);
// ---------- seabed with moving caustics ----------
const seabedY = (x, z) => 0.35 * Math.sin(x * 0.25) * Math.cos(z * 0.2) + 0.15 * Math.sin(x * 0.7 + z * 0.5);
// Caustics = bright lines where two Voronoi cells meet (distance to 2nd nearest
// point minus nearest is small). Points wrap, so the texture tiles seamlessly.
function causticsTexture() {
const S = 256, P = 24, pts = [];
for (let i = 0; i < P; i++) pts.push([rand() * S, rand() * S]);
const c = document.createElement('canvas');
c.width = c.height = S;
const g = c.getContext('2d');
const img = g.createImageData(S, S);
for (let y = 0; y < S; y++) {
for (let x = 0; x < S; x++) {
let d1 = 1e9, d2 = 1e9;
for (let i = 0; i < P; i++) {
let dx = Math.abs(x - pts[i][0]); dx = Math.min(dx, S - dx);
let dy = Math.abs(y - pts[i][1]); dy = Math.min(dy, S - dy);
const d = dx * dx + dy * dy;
if (d < d1) { d2 = d1; d1 = d; } else if (d < d2) d2 = d;
}
const v = Math.max(0, 1 - (Math.sqrt(d2) - Math.sqrt(d1)) / 7);
const o = (y * S + x) * 4, b = Math.round(255 * v * v);
img.data[o] = img.data[o + 1] = img.data[o + 2] = b;
img.data[o + 3] = 255;
}
}
g.putImageData(img, 0, 0);
const t = new THREE.CanvasTexture(c);
t.wrapS = t.wrapT = THREE.RepeatWrapping;
t.repeat.set(10, 10);
return t;
}
const caustics = causticsTexture();
const seabedGeo = new THREE.PlaneGeometry(90, 90, 90, 90);
seabedGeo.rotateX(-Math.PI / 2);
const sp = seabedGeo.attributes.position;
for (let i = 0; i < sp.count; i++) sp.setY(i, seabedY(sp.getX(i), sp.getZ(i)));
seabedGeo.computeVertexNormals();
scene.add(new THREE.Mesh(seabedGeo, new THREE.MeshStandardMaterial({
color: 0xa8956b, roughness: 1, emissive: 0x7fd6ff, emissiveMap: caustics, emissiveIntensity: 0.18,
})));
// Rocks the reef grows around.
const rockMat = new THREE.MeshStandardMaterial({ color: 0x5b5a55, roughness: 1, flatShading: true });
for (let i = 0; i < 16; i++) {
const geo = new THREE.DodecahedronGeometry(1, 1);
const p = geo.attributes.position, k = rand() * 10;
// Faces do not share vertices here, so the bumps must depend on position only:
// copies of the same corner then move together and the rock stays closed.
for (let v = 0; v < p.count; v++) {
const x = p.getX(v), y = p.getY(v), z = p.getZ(v);
const f = 1 + 0.18 * Math.sin(x * 3.1 + k) * Math.cos(y * 2.7 + z * 2.3 + k);
p.setXYZ(v, x * f, y * f, z * f);
}
geo.computeVertexNormals();
const rock = new THREE.Mesh(geo, rockMat);
const a = rand() * Math.PI * 2, r = 2 + rand() * 11, x = Math.cos(a) * r, z = Math.sin(a) * r;
const s = 0.6 + rand() * 1.3;
rock.scale.set(s * (1 + rand() * 0.5), s * 0.6, s);
rock.position.set(x, seabedY(x, z) + s * 0.15, z);
rock.rotation.y = rand() * 6.28;
scene.add(rock);
}
// ---------- light rays from the surface ----------
function rayTexture() {
const c = document.createElement('canvas');
c.width = 64; c.height = 256;
const g = c.getContext('2d');
const v = g.createLinearGradient(0, 0, 0, 256);
v.addColorStop(0, 'rgba(255,255,255,0.9)'); v.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = v; g.fillRect(0, 0, 64, 256);
g.globalCompositeOperation = 'destination-in';
const h = g.createLinearGradient(0, 0, 64, 0);
h.addColorStop(0, 'rgba(0,0,0,0)'); h.addColorStop(0.5, 'rgba(0,0,0,1)'); h.addColorStop(1, 'rgba(0,0,0,0)');
g.fillStyle = h; g.fillRect(0, 0, 64, 256);
return new THREE.CanvasTexture(c);
}
const rayTex = rayTexture();
const rays = [];
for (let i = 0; i < 7; i++) {
const ray = new THREE.Mesh(new THREE.PlaneGeometry(2.5 + rand() * 2, 40), new THREE.MeshBasicMaterial({
map: rayTex, color: 0xbff4ff, transparent: true, opacity: 0.15, blending: THREE.AdditiveBlending, depthWrite: false, fog: false,
}));
ray.position.set((rand() - 0.5) * 30, 18, (rand() - 0.5) * 30);
ray.userData.phase = rand() * 6.28;
scene.add(ray);
rays.push(ray);
}
// ---------- coral ----------
// Every branch is one segment. Colonies start at different times; within a
// colony each child starts when its parent is three quarters grown.
const BLEACHED = new THREE.Color(0xe9e4d8);
const segs = [];
const colonies = [];
function branch(from, dir, len, rad, depth, maxDepth, col, start) {
const to = from.clone().addScaledVector(dir, len);
const s = { from, dir: dir.clone(), len, rad, depth, col, start, end: start + col.segTime * (0.8 + rand() * 0.4), tip: depth === maxDepth, stump: depth === 0 && col.stump };
segs.push(s);
if (depth >= maxDepth) return;
const kids = depth === 0 ? col.firstKids : (rand() < 0.65 ? 2 : 3);
for (let k = 0; k < kids; k++) {
let nd;
if (col.plane) {
// Sea fan: turn only around the fan's normal, so every branch stays in one flat plane.
nd = dir.clone().applyAxisAngle(col.plane, (rand() - 0.5) * 1.2).normalize();
if (nd.y < 0.15) nd.applyAxisAngle(col.plane, nd.x * (col.plane.z >= 0 ? 0.6 : -0.6)).normalize();
} else {
const axis = new THREE.Vector3(rand() - 0.5, rand() * 0.3, rand() - 0.5).normalize();
nd = dir.clone().applyAxisAngle(axis, (0.4 + rand() * 0.5) * (rand() < 0.5 ? 1 : -1)).normalize();
nd.y = Math.max(nd.y, 0.2);
nd.normalize();
}
branch(to.clone(), nd, len * (0.66 + rand() * 0.14), rad * 0.68, depth + 1, maxDepth, col, s.start + (s.end - s.start) * 0.75);
}
}
function spot(rMin, rMax) {
const a = rand() * Math.PI * 2, r = rMin + rand() * (rMax - rMin), x = Math.cos(a) * r, z = Math.sin(a) * r;
return new THREE.Vector3(x, seabedY(x, z) - 0.05, z);
}
// Staghorn: bushy branching coral that is already there as bleached stumps.
for (let i = 0; i < 11; i++) {
const col = { color: new THREE.Color(pick(['#ff6f61', '#ff9c4a', '#f472b6', '#c084fc', '#facc15'])), start: 0.06 + rand() * 0.32, segTime: 0.11, firstKids: 4, amp: 1, stump: true };
colonies.push(col);
branch(spot(1.5, 11), new THREE.Vector3(0, 1, 0), 1.3 + rand() * 0.7, 0.2, 0, 4, col, col.start);
}
// Sea fans: flat, fine-branched, swaying more.
for (let i = 0; i < 6; i++) {
const a = rand() * Math.PI;
const col = { color: new THREE.Color(pick(['#a855f7', '#e11d48', '#f97316'])), start: 0.3 + rand() * 0.25, segTime: 0.09, firstKids: 3, amp: 1.5, plane: new THREE.Vector3(Math.cos(a), 0, Math.sin(a)) };
colonies.push(col);
branch(spot(4, 12), new THREE.Vector3(0, 1, 0), 1.1 + rand() * 0.5, 0.09, 0, 4, col, col.start);
}
// Tube anemones: clusters of single tubes with bulb tips that sway a lot.
for (let i = 0; i < 8; i++) {
const col = { color: new THREE.Color(pick(['#2dd4bf', '#4ade80', '#fde047', '#38bdf8'])), start: 0.22 + rand() * 0.35, segTime: 0.16, firstKids: 0, amp: 3 };
colonies.push(col);
const c = spot(2, 12);
for (let k = 0; k < 14; k++) {
const a = rand() * 6.28, r = rand() * 0.7, x = c.x + Math.cos(a) * r, z = c.z + Math.sin(a) * r;
const dir = new THREE.Vector3((rand() - 0.5) * 0.3, 1, (rand() - 0.5) * 0.3).normalize();
branch(new THREE.Vector3(x, seabedY(x, z) - 0.05, z), dir, 0.7 + rand() * 1.1, 0.07, 0, 0, col, col.start + rand() * 0.05);
}
}
const SEGS = segs.length;
const segMesh = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.72, 1, 1, 7, 1), new THREE.MeshStandardMaterial({ roughness: 0.6 }), SEGS);
segMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
const tips = segs.filter(s => s.tip);
const tipMesh = new THREE.InstancedMesh(new THREE.SphereGeometry(1, 10, 8), new THREE.MeshStandardMaterial({ roughness: 0.45 }), tips.length);
tipMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(segMesh, tipMesh);
// Brain / boulder corals: one bumpy sphere geometry, instanced and squashed.
const brainGeo = new THREE.IcosahedronGeometry(1, 3);
const bp = brainGeo.attributes.position, bv = new THREE.Vector3();
for (let i = 0; i < bp.count; i++) {
bv.fromBufferAttribute(bp, i);
bv.multiplyScalar(1 + 0.07 * Math.sin(bv.x * 9) * Math.sin(bv.y * 9) * Math.sin(bv.z * 9));
bp.setXYZ(i, bv.x, bv.y, bv.z);
}
brainGeo.computeVertexNormals();
const brains = [];
for (let i = 0; i < 12; i++) brains.push({ pos: spot(1, 12), s: 0.8 + rand() * 1, start: 0.1 + rand() * 0.4, color: new THREE.Color(pick(['#a3b86c', '#d6a35c', '#8fbf9f', '#c98f6b'])), rot: rand() * 6.28 });
const brainMesh = new THREE.InstancedMesh(brainGeo, new THREE.MeshStandardMaterial({ roughness: 0.9 }), brains.length);
scene.add(brainMesh);
// ---------- fish ----------
function fishGeometry() {
const N = [0.5, 0, 0], T = [0, 0.15, 0], B = [0, -0.13, 0], L = [0, 0, -0.045], R = [0, 0, 0.045], K = [-0.36, 0, 0], FT = [-0.6, 0.16, 0], FB = [-0.6, -0.16, 0];
const tris = [N, T, R, N, R, B, N, B, L, N, L, T, K, R, T, K, B, R, K, L, B, K, T, L, K, FT, FB];
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute([].concat.apply([], tris), 3));
g.computeVertexNormals();
return g;
}
const SCHOOLS = [
{ color: '#facc15', n: 18, r: 9, h: 3.2, speed: 0.22, size: 0.9, th: 0.5 },
{ color: '#38bdf8', n: 26, r: 6.5, h: 2.2, speed: -0.3, size: 0.6, th: 0.6 },
{ color: '#fb923c', n: 14, r: 11, h: 4.5, speed: 0.17, size: 1, th: 0.7 },
{ color: '#e2e8f0', n: 30, r: 13, h: 6, speed: -0.14, size: 0.55, th: 0.8 },
];
const fish = [];
SCHOOLS.forEach((sc, k) => {
sc.phase = rand() * 6.28;
for (let j = 0; j < sc.n; j++) fish.push({ k, j, off: new THREE.Vector3((rand() - 0.5) * 3, (rand() - 0.5) * 1.4, (rand() - 0.5) * 3), w: rand() * 6.28, th: sc.th + j * 0.004 });
});
// Flat colour (still fogged with distance) keeps the fish bright and readable against the reef.
const fishMesh = new THREE.InstancedMesh(fishGeometry(), new THREE.MeshBasicMaterial({ side: THREE.DoubleSide }), fish.length);
fishMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
fish.forEach((f, i) => fishMesh.setColorAt(i, new THREE.Color(SCHOOLS[f.k].color)));
scene.add(fishMesh);
// ---------- bubbles and marine snow ----------
function dotTexture() {
const c = document.createElement('canvas');
c.width = c.height = 32;
const g = c.getContext('2d'), r = g.createRadialGradient(16, 16, 0, 16, 16, 16);
r.addColorStop(0, 'rgba(255,255,255,1)'); r.addColorStop(0.5, 'rgba(255,255,255,0.5)'); r.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = r; g.fillRect(0, 0, 32, 32);
return new THREE.CanvasTexture(c);
}
const dotTex = dotTexture();
const BUB = 90, bubPos = new Float32Array(BUB * 3), bubBase = [];
for (let i = 0; i < BUB; i++) {
const b = spot(1, 11);
bubBase.push(b);
bubPos.set([b.x, b.y + rand() * 16, b.z], i * 3);
}
const bubGeo = new THREE.BufferGeometry();
bubGeo.setAttribute('position', new THREE.BufferAttribute(bubPos, 3));
const bubbles = new THREE.Points(bubGeo, new THREE.PointsMaterial({ size: 0.22, map: dotTex, color: 0xdff9ff, transparent: true, opacity: 0, depthWrite: false }));
scene.add(bubbles);
const SNOW = 500, snowPos = new Float32Array(SNOW * 3);
for (let i = 0; i < SNOW; i++) snowPos.set([(rand() - 0.5) * 50, rand() * 18, (rand() - 0.5) * 50], i * 3);
const snowGeo = new THREE.BufferGeometry();
snowGeo.setAttribute('position', new THREE.BufferAttribute(snowPos, 3));
scene.add(new THREE.Points(snowGeo, new THREE.PointsMaterial({ size: 0.07, map: dotTex, color: 0xcfefff, transparent: true, opacity: 0.55, depthWrite: false })));
// ---------- scroll ----------
gsap.registerPlugin(ScrollTrigger);
const form = { t: 0 };
gsap.to(form, {
t: 1, ease: 'none',
scrollTrigger: { trigger: stage, start: 'top top', end: '+=450%', pin: true, scrub: reduceMotion ? true : 1 },
});
const pointer = { x: 0, y: 0, sx: 0, sy: 0 };
stage.addEventListener('pointermove', e => {
if (e.pointerType !== 'mouse') return;
const r = stage.getBoundingClientRect();
pointer.x = ((e.clientX - r.left) / r.width - 0.5) * 2;
pointer.y = ((e.clientY - r.top) / r.height - 0.5) * 2;
});
stage.addEventListener('pointerleave', () => { pointer.x = pointer.y = 0; });
let visible = true;
new IntersectionObserver(e => { visible = e[0].isIntersecting; }).observe(stage);
function resize() {
const w = canvas.clientWidth, h = canvas.clientHeight;
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
// ---------- per-frame update ----------
const dummy = new THREE.Object3D(), UP = new THREE.Vector3(0, 1, 0);
const A = new THREE.Vector3(), Bv = new THREE.Vector3(), D = new THREE.Vector3(), S1 = new THREE.Vector3(), S2 = new THREE.Vector3(), tmp = new THREE.Color();
const ZERO = new THREE.Matrix4().makeScale(0, 0, 0);
let time = 0, lastColorT = -1;
// Water movement: a function of position only, so connected branches bend together.
function sway(p, amp, out) {
const k = Math.max(0, p.y) * amp;
return out.set(Math.sin(time * 0.9 + p.y * 0.7 + p.x * 0.3) * 0.05 * k, 0, Math.cos(time * 0.7 + p.y * 0.6 + p.z * 0.3) * 0.04 * k);
}
const colonyHealth = col => smooth(col.start - 0.02, col.start + 0.25, form.t);
function updateCoral(t) {
let ti = 0;
for (let i = 0; i < SEGS; i++) {
const s = segs[i];
const e = smooth(s.start, s.end, t);
const frac = s.stump ? 0.4 + 0.6 * e : e;
if (frac < 0.002) {
segMesh.setMatrixAt(i, ZERO);
if (s.tip) tipMesh.setMatrixAt(ti++, ZERO);
continue;
}
A.copy(s.from).add(sway(s.from, s.col.amp, S1));
Bv.copy(s.from).addScaledVector(s.dir, s.len * frac);
Bv.add(sway(Bv, s.col.amp, S2));
D.subVectors(Bv, A);
const L = D.length(), rad = s.rad * (0.55 + 0.45 * Math.max(e, s.stump ? 0.4 : 0));
dummy.position.copy(A).addScaledVector(D, 0.5);
dummy.quaternion.setFromUnitVectors(UP, D.multiplyScalar(1 / L));
dummy.scale.set(rad, L, rad);
dummy.updateMatrix();
segMesh.setMatrixAt(i, dummy.matrix);
if (s.tip) {
dummy.position.copy(Bv);
dummy.scale.setScalar(s.rad * 1.6 * smooth(0.6, 1, e) + 0.0001);
dummy.updateMatrix();
tipMesh.setMatrixAt(ti++, dummy.matrix);
}
}
segMesh.instanceMatrix.needsUpdate = true;
tipMesh.instanceMatrix.needsUpdate = true;
brains.forEach((b, i) => {
const g = 0.35 + 0.65 * smooth(b.start, b.start + 0.35, t);
dummy.position.copy(b.pos);
dummy.quaternion.setFromAxisAngle(UP, b.rot);
dummy.scale.set(b.s * g, b.s * g * 0.62, b.s * g);
dummy.updateMatrix();
brainMesh.setMatrixAt(i, dummy.matrix);
});
brainMesh.instanceMatrix.needsUpdate = true;
}
// Colour returns per colony: bleached white to its living colour (tips a little lighter).
function updateColours(t) {
let ti = 0;
for (let i = 0; i < SEGS; i++) {
const s = segs[i];
tmp.copy(BLEACHED).lerp(s.col.color, colonyHealth(s.col));
segMesh.setColorAt(i, tmp);
if (s.tip) tipMesh.setColorAt(ti++, tmp.lerp(BLEACHED, 0.25));
}
brains.forEach((b, i) => brainMesh.setColorAt(i, tmp.copy(BLEACHED).lerp(b.color, smooth(b.start, b.start + 0.3, t))));
segMesh.instanceColor.needsUpdate = tipMesh.instanceColor.needsUpdate = brainMesh.instanceColor.needsUpdate = true;
}
function updateFish(t) {
let shown = 0;
fish.forEach((f, i) => {
const sc = SCHOOLS[f.k];
const vis = smooth(f.th, f.th + 0.05, t);
if (vis < 0.01) { fishMesh.setMatrixAt(i, ZERO); return; }
if (vis > 0.5) shown++;
const ang = time * sc.speed + sc.phase;
const c = Math.cos(ang), s = Math.sin(ang);
// Offsets rotate with the school, so the formation turns as one.
const ox = f.off.x * c - f.off.z * s, oz = f.off.x * s + f.off.z * c;
const wob = Math.sin(time * 2 + f.w);
dummy.position.set(Math.cos(ang) * (sc.r + f.off.x * 0.3) + ox * 0.4, sc.h + f.off.y + wob * 0.15, Math.sin(ang) * (sc.r + f.off.z * 0.3) + oz * 0.4);
const dir = Math.sign(sc.speed);
const hx = -Math.sin(ang) * dir, hz = Math.cos(ang) * dir;
dummy.rotation.set(0, -Math.atan2(hz, hx) + wob * 0.12, 0);
dummy.scale.setScalar(sc.size * 1.35 * vis);
dummy.updateMatrix();
fishMesh.setMatrixAt(i, dummy.matrix);
});
fishMesh.instanceMatrix.needsUpdate = true;
return shown;
}
const chapterRanges = [[0.02, 0.2], [0.24, 0.46], [0.5, 0.72], [0.76, 2]];
const clock = new THREE.Clock();
function frame() {
requestAnimationFrame(frame);
const dt = Math.min(clock.getDelta(), 0.05);
if (!visible) return;
if (!reduceMotion) time += dt;
const t = form.t;
updateCoral(t);
if (Math.abs(t - lastColorT) > 0.002) { updateColours(t); lastColorT = t; }
const fishCount = updateFish(t);
// Bubbles rise from the coral, more of them as the reef recovers.
bubbles.material.opacity = 0.15 + 0.6 * t;
if (!reduceMotion) {
for (let i = 0; i < BUB; i++) {
let y = bubPos[i * 3 + 1] + dt * (1 + (i % 5) * 0.3);
if (y > 18) y = bubBase[i].y;
bubPos[i * 3 + 1] = y;
bubPos[i * 3] = bubBase[i].x + Math.sin(time * 2 + i) * 0.1;
}
bubGeo.attributes.position.needsUpdate = true;
caustics.offset.set(time * 0.02, time * 0.013);
}
// Camera circles down into the reef.
pointer.sx += (pointer.x - pointer.sx) * 0.05;
pointer.sy += (pointer.y - pointer.sy) * 0.05;
const ang = 0.35 + t * 1.5 + pointer.sx * 0.08;
const rad = 27 - t * 8;
camera.position.set(Math.sin(ang) * rad, 11 - t * 4 + Math.sin(time * 0.3) * 0.3, Math.cos(ang) * rad);
camera.lookAt(0, 2.2 + t * 1.3 - pointer.sy * 0.6, 0);
rays.forEach((r, i) => {
r.lookAt(camera.position.x, r.position.y, camera.position.z);
r.material.opacity = 0.1 + 0.07 * Math.sin(time * 0.5 + r.userData.phase);
});
pctEl.textContent = Math.round(t * 100);
fishEl.textContent = fishCount;
barEl.style.transform = 'scaleX(' + t.toFixed(4) + ')';
introEl.classList.toggle('is-hidden', t > 0.02);
chapters.forEach((el, i) => el.classList.toggle('is-on', t > chapterRanges[i][0] && t < chapterRanges[i][1]));
renderer.render(scene, camera);
}
resize();
window.addEventListener('resize', resize);
frame();Extend with AI
Take This Snippet Further With AI
You do not have to work out procedural coral and instancing from scratch. Paste this snippet's HTML, CSS and JS into an AI assistant like Claude and ask it how the recursive branching works, why the sway keeps branches joined, or how the Voronoi caustics texture is made. It can also help you take it further: add a sea turtle that glides through once the reef is healthy, let fish scatter away from the mouse, add a diver silhouette with a bubble trail, or show real reef facts in the chapter captions.
Prompt to recreate it
Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:
Build a scroll-driven "coral reef restoration" scene in plain HTML, CSS and JavaScript with Three.js r128, GSAP and ScrollTrigger from a CDN.
Requirements:
- A pinned full-screen stage (scrub 1, end +=450%) where a tween takes one value t from 0 to 1. A requestAnimationFrame loop also keeps a running time for ambient motion. Pause rendering off screen with IntersectionObserver; with prefers-reduced-motion freeze the ambient time and use scrub: true.
- Underwater look: a CSS gradient behind a transparent canvas, Fog in the water colour, hemisphere and directional light, a sandy seabed with gentle dunes, jittered rock dodecahedrons, a seamless Voronoi caustics canvas texture used as the seabed emissive map and scrolled over time, additive light-ray planes that face the camera, rising bubbles and drifting marine snow.
- Coral from a recursive branch() function (segments with start and end times; a child starts when its parent is 75% grown): bushy staghorn colonies that begin as bleached stumps at 40% length, flat sea fans that only turn around their own normal, and clusters of single tube anemones. Draw all segments with one tapered-cylinder InstancedMesh and leaf tips with one sphere InstancedMesh, plus instanced bumpy brain corals that grow from 35% scale.
- Sway: a function of position and time that offsets both ends of every segment, scaled by height and a per-colony amplitude, so connected branches bend together.
- Colour: blend every colony from bleached off-white to its living colour as t passes the colony start time; only rewrite instance colours when t changes.
- Four fish schools (one InstancedMesh of a hand-built low-poly fish) circling the reef at their own radius, height and speed, with offsets that rotate with the school, appearing one fish at a time from about 50% to 80% of the scroll.
- Camera circles down from far and high to close and low as t grows, with a small mouse-look offset.
- Overlay: an intro card that fades on scroll, four chapter captions at set t ranges (Bare rock, First polyps, Branching out, Life returns), and a HUD with reef health %, visible fish count and a progress bar.
- Use a seeded random so the reef is the same on every load. Scrolling back up must reverse everything.Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.