three.js scroll animation in Next.js: a complete, working client component
By Md Mahafuj Alam · Updated
When a live three.js scene is the right choice
A scroll story can be built three ways: a canvas that scrubs an image sequence, a video, or a real-time 3D scene. Frames give you photoreal footage but a fixed camera. A live scene costs more to build, but it weighs far less than hundreds of frames, stays sharp at any screen size, reacts to the pointer and can run physics. The trade-offs are laid out in image sequence vs video vs three.js.
Choose three.js when the subject can be built from simple shapes and good materials (coins, cards, a bottle, a product on a plinth), when the visitor should be able to touch it, or when you need the story to rewind exactly as they scroll back. The component on this page is the skeleton for that: one scene, one camera path, premium lighting and every production guard a real site needs.
If you are planning the whole site with Claude, start from the pillar guide, how to build a 3D website with Claude, and come back here for the scene itself.
Install three.js and set up the page
three.js ships its own entry points for addons such as RoomEnvironment and HDRLoader under three/addons/. Install the library and its TypeScript types in your Next.js project.
npm install three
npm install -D @types/threeThe component below starts with 'use client' because it needs the browser: WebGL, window, observers and effects. All the three.js work happens inside useEffect, which never runs during server rendering or a static export, so the module is safe to import from a server page. Use it like any other component:
import ScrollScene from './ScrollScene';
export default function Page() {
return (
<main>
<section style={{ height: '100svh' }}>Intro copy</section>
<ScrollScene poster="/poster.webp" />
<section style={{ height: '100svh' }}>What comes next</section>
</main>
);
}poster is a still render of the scene, shown when WebGL is unavailable. Take a screenshot of the scene at its best moment and save it as WebP in public/.
The full component
This is the whole file. It type-checks against three.js r186 with strict TypeScript. The numbered comments match the sections that follow.
'use client';
import { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
// Camera keyframes: where the camera sits and what it looks at, from scroll 0 to 1.
const CAMERA_PATH = new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 1.2, 7),
new THREE.Vector3(3.5, 1.6, 4.5),
new THREE.Vector3(2.5, 3.2, -1.5),
new THREE.Vector3(-1.5, 1.4, 3),
]);
const LOOK_AT = new THREE.Vector3(0, 0.9, 0);
export default function ScrollScene({ poster }: { poster: string }) {
const sectionRef = useRef<HTMLElement>(null);
const mountRef = useRef<HTMLDivElement>(null);
const [fallback, setFallback] = useState(false);
useEffect(() => {
const section = sectionRef.current;
const mount = mountRef.current;
if (!section || !mount) return;
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// 1. Renderer. The constructor throws if WebGL is unavailable.
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
} catch {
setFallback(true);
return;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.toneMappingExposure = 1;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
mount.appendChild(renderer.domElement);
// 2. Scene, camera and image-based lighting from RoomEnvironment.
const scene = new THREE.Scene();
scene.background = new THREE.Color('#e9e4dc');
const camera = new THREE.PerspectiveCamera(35, 1, 0.1, 100);
const pmrem = new THREE.PMREMGenerator(renderer);
const room = new RoomEnvironment();
const envMap = pmrem.fromScene(room, 0.04).texture;
scene.environment = envMap;
scene.environmentIntensity = 0.9;
// One key light for shape and a soft contact shadow.
const sun = new THREE.DirectionalLight('#fff4e6', 2.2);
sun.position.set(4, 7, 3);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -4;
sun.shadow.camera.right = 4;
sun.shadow.camera.top = 4;
sun.shadow.camera.bottom = -4;
sun.shadow.bias = -0.0005;
sun.shadow.radius = 4;
scene.add(sun);
// 3. Materials and objects.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({ color: '#e9e4dc', roughness: 0.95 }),
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const hero = new THREE.Mesh(
new THREE.TorusKnotGeometry(0.7, 0.24, 220, 32),
new THREE.MeshPhysicalMaterial({ color: '#c9a227', metalness: 1, roughness: 0.28, clearcoat: 0.6, clearcoatRoughness: 0.2 }),
);
hero.position.y = 1.1;
hero.castShadow = true;
scene.add(hero);
const plinth = new THREE.Mesh(
new THREE.CylinderGeometry(1.1, 1.2, 0.3, 64),
new THREE.MeshStandardMaterial({ color: '#d8d2c8', roughness: 0.7 }),
);
plinth.position.y = 0.15;
plinth.castShadow = true;
plinth.receiveShadow = true;
scene.add(plinth);
// Put the camera and the hero where scroll position p (0 to 1) says.
const place = (p: number) => {
CAMERA_PATH.getPointAt(p, camera.position);
camera.lookAt(LOOK_AT);
hero.rotation.y = p * Math.PI * 1.5;
};
// 4. Size the canvas to its box, not the window.
const resize = () => {
const { clientWidth: w, clientHeight: h } = mount;
if (!w || !h) return;
renderer.setSize(w, h);
camera.aspect = w / h;
// Portrait screens: widen the view so the subject still fits.
camera.fov = w / h < 1 ? 50 : 35;
camera.updateProjectionMatrix();
if (reduceMotion) {
place(0.35);
renderer.render(scene, camera);
}
};
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(mount);
resize();
// 5. Scroll progress: 0 when the section top hits the viewport top, 1 when its bottom reaches the viewport bottom.
let target = 0;
let progress = 0;
const readScroll = () => {
const rect = section.getBoundingClientRect();
const distance = rect.height - window.innerHeight;
target = distance > 0 ? THREE.MathUtils.clamp(-rect.top / distance, 0, 1) : 0;
};
// 6. Render loop with frame-rate-independent smoothing.
const timer = new THREE.Timer();
const tick = (time: number) => {
timer.update(time);
const dt = Math.min(timer.getDelta(), 0.1);
progress += (target - progress) * (1 - Math.exp(-dt * 6));
place(progress);
renderer.render(scene, camera);
};
// 7. Only run the loop while the section is on screen.
const visibility = new IntersectionObserver(
([entry]) => {
if (reduceMotion) return;
if (entry.isIntersecting) {
readScroll();
timer.reset();
renderer.setAnimationLoop(tick);
} else {
renderer.setAnimationLoop(null);
}
},
{ rootMargin: '100px 0px' },
);
visibility.observe(section);
if (!reduceMotion) {
window.addEventListener('scroll', readScroll, { passive: true });
readScroll();
}
// 8. Clean up everything on unmount.
return () => {
renderer.setAnimationLoop(null);
visibility.disconnect();
resizeObserver.disconnect();
window.removeEventListener('scroll', readScroll);
scene.traverse((obj) => {
if (obj instanceof THREE.Mesh) {
obj.geometry.dispose();
const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
materials.forEach((m: THREE.Material) => m.dispose());
}
});
envMap.dispose();
room.dispose();
pmrem.dispose();
timer.dispose();
renderer.dispose();
renderer.domElement.remove();
};
}, []);
return (
<section ref={sectionRef} style={{ height: '400vh', position: 'relative' }}>
<div style={{ position: 'sticky', top: 0, height: '100svh' }}>
{fallback ? (
<img src={poster} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<div ref={mountRef} style={{ width: '100%', height: '100%' }} />
)}
</div>
</section>
);
}The layout does the scroll work. The section is 400vh tall and the canvas wrapper is position: sticky at the top, so the canvas stays pinned while the visitor scrolls through three extra screen heights. More height means a slower, more deliberate camera move. No pinning library is needed.
Lighting and materials that look premium
Most three.js scenes look cheap for one reason: the lighting is a single ambient light plus a directional light, and the materials have nothing to reflect. Real metal, glass and lacquer are mostly reflections. Give them an environment.
Environment lighting with PMREMGenerator
The RoomEnvironment addon is a small procedural room with bright panels. PMREMGenerator turns it into a pre-filtered environment map, and scene.environment applies it to every physically based material. That one line is what makes the gold knot read as metal. The second argument to fromScene is a blur (sigma); a small value softens the reflections without losing the panels.
For a specific mood, swap the room for a studio HDRI. Since r180 the loader is called HDRLoader (the old RGBELoader is deprecated). The pattern from the HDRLoader docs:
import * as THREE from 'three';
import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';
export async function loadStudioHdri(scene: THREE.Scene) {
const hdr = await new HDRLoader().loadAsync('/hdri/studio_1k.hdr');
hdr.mapping = THREE.EquirectangularReflectionMapping;
scene.environment = hdr;
return () => hdr.dispose();
}
export async function loadColourTexture(url: string) {
const tex = await new THREE.TextureLoader().loadAsync(url);
tex.colorSpace = THREE.SRGBColorSpace;
return tex;
}A 1K HDRI is enough for reflections when you do not show it as the background. Larger files cost download time and GPU memory for detail nobody sees.
Colour management and tone mapping
The WebGLRenderer docs give outputColorSpace a default of SRGBColorSpace and toneMapping a default of NoToneMapping. The component sets both explicitly so the intent is clear. Without tone mapping, bright highlights clip to flat white. NeutralToneMapping rolls them off while keeping your brand colours close to their hex values, which suits product work. ACESFilmicToneMapping and AgXToneMapping give a more filmic look but shift hues.
The colour management manual has the rule for textures: colour maps (base colour, emissive) are sRGB and need texture.colorSpace = SRGBColorSpace; data maps (normal, roughness, metalness) stay linear. Getting this wrong makes textures look washed out or muddy, which is what loadColourTexture above guards against.
One key light, real shadows
- One directional key light casts the shadow. The environment does the fill, so you do not need an ambient light.
- Fit the shadow camera to the subject (here 8 × 8 units). A tight box gives sharp shadows from a 1024 map; a loose box wastes resolution.
- Set a small negative bias to remove shadow acne, the striped self-shadowing on curved surfaces.
- Use MeshPhysicalMaterial for hero objects.
clearcoatadds the lacquer layer that makes metal and plastic read as expensive. Keep roughness above about 0.2 so reflections stay soft.
Drive the camera from scroll progress
The camera never reads scroll events directly. The scroll listener only stores a target between 0 and 1. The render loop eases the current progress towards it and places the camera. Three details make it feel right:
- Progress from the section, not the page.
-rect.top / (rect.height - innerHeight)is 0 when the section's top meets the viewport top and 1 when its bottom meets the viewport bottom: exactly the sticky range. - A curve, not straight lines.
CatmullRomCurve3.getPointAtspaces points by arc length, so the camera moves at an even speed through every keyframe. Edit the fourVector3s to change the shot. - Frame-rate-independent easing.
1 - Math.exp(-dt * 6)eases by the same amount per second on a 60 Hz laptop and a 120 Hz phone. A fixed factor such as0.1per frame runs twice as fast on the 120 Hz screen.
Because everything is a function of progress, scrolling back rewinds the scene exactly. That is the property MANJARI's feature list describes as "everything is driven by scroll progress".
The same thing with GSAP ScrollTrigger
If the site already uses GSAP, let ScrollTrigger measure progress. self.progress runs from 0 at start to 1 at end, and kill() removes its listeners. Call this instead of the scroll listener and assign the value to target:
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
export function trackProgress(section: HTMLElement, onProgress: (p: number) => void) {
const trigger = ScrollTrigger.create({
trigger: section,
start: 'top top',
end: 'bottom bottom',
onUpdate: (self) => onProgress(self.progress),
});
return () => trigger.kill();
}Leave scrub off here: the render loop already smooths the value, and smoothing twice makes the camera feel late. Wiring ScrollTrigger to Lenis smooth scrolling is covered in GSAP ScrollTrigger and Lenis in Next.js.
Performance: render only on screen, cap the pixel ratio
A WebGL loop that runs while the visitor reads the pricing section burns battery for nothing. The component uses an IntersectionObserver to start the loop with setAnimationLoop(tick) when the section enters view and stop it with setAnimationLoop(null) when it leaves. The 100 px rootMargin starts it just before it appears, so the first visible frame is already correct.
| Guard | What it saves | Where in the component |
|---|---|---|
| Pixel ratio capped at 2 | A 3× phone renders 2.25× fewer pixels than at native ratio (9 vs 4 per CSS pixel) | Step 1 |
| Loop only while visible | GPU and battery for the rest of the page | Step 7 |
| Shadow map 1024², tight frustum | Fill rate and memory versus a 2048² or 4096² map | Step 2 |
| ResizeObserver on the box | Re-renders only when the canvas size really changes | Step 4 |
| Delta clamped to 0.1 s | No camera jump after a tab switch | Step 6 |
On phones, consider a lower cap such as 1.5 and fewer segments on curved geometry. MANJARI and Zelvo both list the same two guards in their features: canvases that render only on screen and a capped pixel ratio. MANJARI also uses fewer particles on lower-power devices and compiles shaders before the loader fades; Zelvo's preloader builds every 3D scene up front. Both avoid the first-scroll stutter you get when three.js compiles a material the first time it is drawn. More mobile tactics are in scroll animation performance on mobile.
Reduced motion and no-WebGL fallbacks
Two visitors must still get a working page. The first has asked their system for reduced motion. The component reads prefers-reduced-motion once, skips the scroll listener and the loop, and renders one still frame at progress 0.35 (re-rendered on resize). The section stays tall, so if you want the copy closer together for these visitors, shorten it with the same media query in CSS.
The second visitor has no WebGL: an old device, a disabled GPU or a locked-down browser. The WebGLRenderer constructor throws when it cannot get a context, so the component catches that, sets fallback and shows the poster image instead of the canvas. MANJARI ships exactly this pair: "reduced-motion and no-WebGL fallback with a static finale frame". The broader pattern is in reduced motion for scroll animation.
Dispose everything on unmount
three.js does not free GPU memory when a component unmounts. Geometries, materials, textures and render targets live on the GPU until you call dispose(). In a Next.js app, client-side navigation unmounts and remounts the component, and React's Strict Mode runs effects twice in development, so a missing cleanup shows up fast as a growing memory graph and, eventually, a lost WebGL context.
- Stop the loop and disconnect both observers and the scroll listener.
- Traverse the scene and dispose each mesh's geometry and materials (a mesh can hold an array of materials).
- Dispose the environment texture, the
RoomEnvironmentand thePMREMGenerator. Its docs note that it is effectively shared, so use one per renderer. - Call
renderer.dispose(), which the docs describe as freeing "the GPU-related resources allocated by this instance", then remove the canvas element.
How the templates use this pattern
Two templates in the catalogue build their heroes as live three.js scenes rather than footage, and their published feature lists show where the skeleton above goes next.
- MANJARI renders a four-chapter hero live in three.js from AI images only (GPT Image 2), with no video. Depth-parallax backdrops come from Depth Anything V2 depth maps, a photographed mango swaps into a procedural 3D mango that splits and bursts into GPU juice droplets, and a flood shader drains to reveal the bottle.
- Zelvo is a clay money town with a scroll-driven camera that pauses softly on each shot. Its realism kit is studio HDRI lighting, ambient occlusion, bloom, SMAA and neutral tone mapping, and every object is built in code with no 3D model files, so colours and shapes are easy to change.
- Orbitly shows a hybrid: a 691-frame image sequence with a real-time three.js light layer on top that changes with each chapter.
Each one ships its full source, so you can read how a production scene handles loading, portrait framing and cleanup. Browse them all in the template catalogue.
Questions, answered.
The questions people ask most about this topic.
01Do I need React Three Fiber for a scroll scene in Next.js?
No. Plain three.js in a useEffect, as in this guide, is enough for one scene and keeps the setup visible. React Three Fiber helps when the scene has many components that share state with the rest of your React tree.
02Which tone mapping should I use for product scenes?
NeutralToneMapping keeps brand colours close to their hex values while softening highlights, which suits products. ACESFilmicToneMapping and AgXToneMapping look more filmic but shift hues. Set renderer.toneMapping and compare on your real colours.
03Why does my three.js scene look washed out?
Usually colour textures are not marked as sRGB. Set texture.colorSpace = THREE.SRGBColorSpace on base colour and emissive maps, keep data maps linear, and leave renderer.outputColorSpace at SRGBColorSpace.
04Will a three.js scene work with output: export in Next.js?
Yes. All WebGL code runs in useEffect on the client, so the static export renders the section and poster markup and the scene starts in the browser. Put HDRIs and textures in public/ and they ship as static files.
05How do I stop the scene stuttering on the first scroll?
Compile materials before the visitor scrolls. Render the scene once while a loader is visible, or call renderer.compile(scene, camera), so shaders are ready before the camera moves.
Keep reading
- Start here · the full workflowHow to Build a 3D Motion Website with ClaudeBuild a 3D motion website with Claude: plan the story, generate keyframes and video, cut frames with ffmpeg, then build it in Next.js with GSAP and Lenis.Read the guide
- Guide · BuildGSAP ScrollTrigger + Lenis in Next.js App RouterSet up GSAP ScrollTrigger and Lenis in the Next.js App Router: useGSAP scoping, the Lenis sync, a root provider, pinning, anchor links and reduced motion.Read the guide
- Guide · PlanningImage sequence vs video vs three.js: choosing a technique for a 3D scroll siteImage sequence vs video scroll vs three.js: how each technique works, and how they compare on smoothness, file size, mobile, realism, effort and LCP.Read the guide