Loading…
← All components

Background · Chrome

Chrome Field

Hundreds of instanced chrome shapes: a fixed background the camera flies through on scroll, or a foreground layer.

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add chrome-field
01

Install

The 3D packages this component is built on.

$ npm install three
02

Add the component

One self-contained file: create components/ChromeFieldDemo.js and paste it in.

components/ChromeFieldDemo.js
1"use client";
2
3import { useEffect, useRef } from "react";
4import * as THREE from "three";
5import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";
6import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
7import dynamic from "next/dynamic";
8
9/**
10 * Lazily loads a client-only scene from /components/3d, skipping SSR
11 * entirely (WebGL has no meaning on the server). `next/dynamic`'s
12 * `ssr: false` option is only valid when the call site is itself inside
13 * a Client Component — which is why this helper lives in a "use client"
14 * file and must only be called from other Client Components.
15 */
16function load3D(importer, { fallbackClassName = "" } = {}) {
17 return dynamic(importer, {
18 ssr: false,
19 loading: () => (
20 <div
21 className={`animate-pulse rounded-[2rem] bg-white/[0.04] ${fallbackClassName}`}
22 />
23 ),
24 });
25}
26
27/**
28 * Field of chrome geometric shapes in plain three.js (no React Three Fiber).
29 * - Primitives (icosahedron, octahedron, torus, rounded box,
30 * cylinder, cone): one geometry and one InstancedMesh per type.
31 * - Chrome = polished metal reflecting a PMREM-filtered RoomEnvironment,
32 * plus cool white lights for crisp highlights on the edges.
33 * - On scroll the camera travels through the cloud with inertia; the pointer
34 * tilts it slightly. Black background and fog.
35 * Without `front`: fixed canvas behind the whole page (-z-10).
36 * With `front`: transparent layer of a few shapes in the foreground, sized to
37 * its parent (e.g. in front of the hero title). The shapes closest to the
38 * camera are out of focus (depth of field): see the "Focus" block below.
39 */
40
41const BLACK = 0x000000;
42
43// Shapes closer than this to the camera are drawn out of focus. Re-evaluated every frame: a shape the
44// camera flies towards while the page scrolls slips out of focus as it comes close.
45const NEAR_DISTANCE = 8.5;
46
47// The blurred shapes are rendered at a fraction of the canvas resolution (a blur needs no detail, and
48// it keeps the extra passes almost free), then blurred twice with a 9-tap separable gaussian.
49const BLUR_SCALE = 0.7;
50
51const BLUR_SPREAD = 2; // gap between taps, in texels of that small target
52
53const BLUR_ITERATIONS = 2;
54
55const quadVertexShader = /* glsl */ `
56varying vec2 vUv;
57void main() {
58 vUv = uv;
59 gl_Position = vec4(position.xy, 0.0, 1.0);
60}
61`;
62
63// Separable gaussian. The target is cleared to transparent black, so color and alpha blur together:
64// the result is premultiplied, edges fade out instead of turning dark.
65const blurFragmentShader = /* glsl */ `
66uniform sampler2D tMap;
67uniform vec2 uStep;
68varying vec2 vUv;
69// Highlights clamped before blurring: a chrome glint is far brighter than 1 (sometimes past what a
70// half float holds), and blurred as is it turns into hard rings and dark outlines
71vec4 tap(vec2 uv) {
72 return min(texture2D(tMap, uv), vec4(1.6, 1.6, 1.6, 1.0));
73}
74void main() {
75 vec4 sum = tap(vUv) * 0.2270270270;
76 sum += (tap(vUv + uStep * 1.0) + tap(vUv - uStep * 1.0)) * 0.1945945946;
77 sum += (tap(vUv + uStep * 2.0) + tap(vUv - uStep * 2.0)) * 0.1216216216;
78 sum += (tap(vUv + uStep * 3.0) + tap(vUv - uStep * 3.0)) * 0.0540540541;
79 sum += (tap(vUv + uStep * 4.0) + tap(vUv - uStep * 4.0)) * 0.0162162162;
80 gl_FragColor = sum;
81}
82`;
83
84// Blurred shapes over the sharp ones. Rendering to a target skips tone mapping and the sRGB output,
85// so they are applied here, on the un-premultiplied color, then premultiplied again for the blending.
86const compositeFragmentShader = /* glsl */ `
87uniform sampler2D tMap;
88varying vec2 vUv;
89void main() {
90 vec4 c = texture2D(tMap, vUv);
91 if (c.a < 0.002) discard;
92 gl_FragColor = vec4(c.rgb / c.a, c.a);
93 #include <tonemapping_fragment>
94 #include <colorspace_fragment>
95 gl_FragColor.rgb *= gl_FragColor.a;
96}
97`;
98
99// One geometry per type, all scaled to roughly fit a sphere of radius ~1.
100// Segment counts kept modest: hundreds of instances are drawn every frame, mostly small on screen.
101function createGeometries() {
102 return [
103 new THREE.IcosahedronGeometry(1, 0),
104 new THREE.OctahedronGeometry(1.05),
105 new THREE.TorusGeometry(0.75, 0.28, 16, 48),
106 new RoundedBoxGeometry(1.3, 1.3, 1.3, 4, 0.18),
107 new THREE.CylinderGeometry(0.6, 0.6, 1.5, 32),
108 new THREE.ConeGeometry(0.75, 1.6, 32),
109 ];
110}
111
112function ChromeField2({ front = false, onReady }) {
113 const hostRef = useRef(null);
114 // onReady : appelé une fois, après la première image dessinée (le loader du hero attend ce signal)
115 const onReadyRef = useRef(onReady);
116
117 useEffect(() => {
118 onReadyRef.current = onReady;
119 }, [onReady]);
120
121 useEffect(() => {
122 // A fresh canvas per mount: its context is released on unmount (forceContextLoss), so a remount
123 // (React StrictMode, HMR, navigation) must not reuse it
124 const host = hostRef.current;
125 if (!host) return undefined;
126 const canvas = document.createElement("canvas");
127 canvas.className = "block h-full w-full";
128 host.appendChild(canvas);
129
130 const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
131 const small = window.innerWidth < 768;
132 const COUNT = front ? (small ? 16 : 42) : small ? 180 : 420;
133 const DEPTH = 120; // depth of the cloud, travelled through as the page scrolls
134 const REST_Z = 12; // camera position at the top of the page
135 const FRONT_TRAVEL = 20; // distance the foreground camera covers over one screen of scroll (past every shape)
136
137 const renderer = new THREE.WebGLRenderer({ canvas, antialias: !front, alpha: front, powerPreference: "high-performance" });
138 // Foreground shapes are large and close to the camera: they cover much of the screen with the costly
139 // chrome shader, so that layer renders at a lower pixel ratio (they move fast, the difference doesn't show)
140 renderer.setPixelRatio(Math.min(window.devicePixelRatio, front ? 1.25 : 1.75));
141 renderer.setClearColor(BLACK, front ? 0 : 1);
142 renderer.outputColorSpace = THREE.SRGBColorSpace;
143 renderer.toneMapping = THREE.ACESFilmicToneMapping;
144 renderer.toneMappingExposure = 1.1;
145
146 const FOG_FAR = 34;
147 const scene = new THREE.Scene();
148 scene.fog = new THREE.Fog(BLACK, 8, FOG_FAR);
149
150 // Chrome reflections: a lit room, prefiltered once with PMREM
151 const pmrem = new THREE.PMREMGenerator(renderer);
152 const room = new RoomEnvironment();
153 const envTarget = pmrem.fromScene(room, 0.04);
154 scene.environment = envTarget.texture;
155 room.dispose();
156 pmrem.dispose();
157
158 // Far plane just past the fog: shapes beyond it would be drawn fully black, so they are clipped instead
159 const camera = new THREE.PerspectiveCamera(42, 1, 0.1, FOG_FAR + 2);
160 camera.position.set(0, 0, 12);
161
162 // White / cool lights: crisp highlights on the edges
163 const key = new THREE.DirectionalLight(0xffffff, 2.4);
164 key.position.set(6, 8, 10);
165 scene.add(key);
166 const rim = new THREE.DirectionalLight(0xcfe0ff, 2);
167 rim.position.set(-8, -3, -6);
168 scene.add(rim);
169 const top = new THREE.DirectionalLight(0xe8f0ff, 1.2);
170 top.position.set(0, 10, 2);
171 scene.add(top);
172 // Lights are filtered by layer like meshes: they must light the out-of-focus layer (1) too
173 [key, rim, top].forEach((light) => light.layers.enableAll());
174
175 const geometries = createGeometries();
176 const material = new THREE.MeshPhysicalMaterial({
177 color: 0xC2C2C2,
178 metalness: 2,
179 roughness: 0.10,
180 envMapIntensity: 1.20,
181 });
182
183 // Position, base orientation, own spin axis/speed, size and type of each shape (drawn once)
184 const data = Array.from({ length: COUNT }, () => {
185 const type = Math.floor(Math.random() * geometries.length);
186 const base = new THREE.Quaternion().setFromEuler(
187 new THREE.Euler(Math.random() * Math.PI, Math.random() * Math.PI, Math.random() * Math.PI)
188 );
189 const axis = new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize();
190 const spin = (0.15 + Math.random() * 0.45) * (Math.random() < 0.5 ? -1 : 1);
191 const bob = Math.random() * Math.PI * 2;
192 if (front) {
193 // Foreground: shapes spread over the whole frame, x/y stored in screen units (-1..1)
194 // and converted at the current aspect ratio so they keep filling the width after a resize
195 return {
196 type, base, axis, spin, bob,
197 nx: (Math.random() * 2 - 1) * 1.05,
198 ny: (Math.random() * 2 - 1) * 1.05,
199 z: -6 + Math.random() * 13,
200 scale: 0.22 + Math.random() * 0.36,
201 };
202 }
203 return {
204 type, base, axis, spin, bob,
205 x: (Math.random() * 2 - 1) * 18,
206 y: (Math.random() * 2 - 1) * 11,
207 z: 6 - Math.random() * DEPTH,
208 scale: 0.26 + Math.random() * 0.34,
209 };
210 });
211
212 // One InstancedMesh per type, sized to the number of shapes of that type
213 const counts = geometries.map((_, type) => data.filter((s) => s.type === type).length);
214 const meshes = geometries.map((geometry, type) => {
215 const mesh = new THREE.InstancedMesh(geometry, material, Math.max(1, counts[type]));
216 mesh.count = counts[type];
217 mesh.frustumCulled = false; // instances are spread across the whole depth
218 scene.add(mesh);
219 return mesh;
220 });
221 // Foreground: a twin InstancedMesh per type on layer 1, for the shapes out of focus. Every shape has a
222 // slot in both; each frame it is drawn in one and collapsed to nothing in the other.
223 // Out of focus, the shapes are satin metal: a polished chrome's crisp reflections would survive the
224 // blur as blotches, a rough surface only keeps its broad light and shade
225 const blurredMaterial = front
226 ? new THREE.MeshStandardMaterial({ color: 0xc2c2c2, metalness: 1, roughness: 0.05, envMapIntensity: 1 })
227 : null;
228 const blurMeshes = front
229 ? geometries.map((geometry, type) => {
230 const mesh = new THREE.InstancedMesh(geometry, blurredMaterial, Math.max(1, counts[type]));
231 mesh.count = counts[type];
232 mesh.frustumCulled = false;
233 mesh.layers.set(1);
234 scene.add(mesh);
235 return mesh;
236 })
237 : null;
238 const hidden = new THREE.Matrix4().makeScale(0, 0, 0);
239
240 const next = new Array(geometries.length).fill(0);
241 data.forEach((s) => {
242 s.index = next[s.type]++;
243 });
244
245 // Instance transforms composed straight into a matrix: an Object3D "dummy" would re-sync its Euler
246 // rotation on every quaternion change, the main per-frame CPU cost with hundreds of shapes
247 const matrix = new THREE.Matrix4();
248 const position = new THREE.Vector3();
249 const quaternion = new THREE.Quaternion();
250 const scale = new THREE.Vector3();
251 const spinQuat = new THREE.Quaternion();
252 const pointer = { x: 0, y: 0, sx: 0, sy: 0 };
253 let scrollTarget = 0;
254 let scrollCurrent = 0;
255
256 const halfTan = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2));
257
258 const place = (t) => {
259 data.forEach((s) => {
260 let { x, y } = s;
261 if (front) {
262 // Half-height of the frame at this shape's depth, seen from the resting camera
263 // (fixed reference: the shapes must not follow the camera when it moves forward)
264 const halfH = (REST_Z - s.z) * halfTan;
265 x = s.nx * halfH * camera.aspect;
266 y = s.ny * halfH;
267 }
268 position.set(x, y + Math.sin(t * 0.6 + s.bob) * 0.25, s.z);
269 spinQuat.setFromAxisAngle(s.axis, t * s.spin);
270 quaternion.copy(s.base).premultiply(spinQuat);
271 scale.setScalar(s.scale);
272 matrix.compose(position, quaternion, scale);
273 if (front) {
274 const blurred = camera.position.z - s.z < NEAR_DISTANCE;
275 meshes[s.type].setMatrixAt(s.index, blurred ? hidden : matrix);
276 blurMeshes[s.type].setMatrixAt(s.index, blurred ? matrix : hidden);
277 } else {
278 meshes[s.type].setMatrixAt(s.index, matrix);
279 }
280 });
281 meshes.forEach((mesh) => {
282 mesh.instanceMatrix.needsUpdate = true;
283 });
284 blurMeshes?.forEach((mesh) => {
285 mesh.instanceMatrix.needsUpdate = true;
286 });
287 };
288
289 // Focus passes (foreground only): two small half-float targets the blur ping-pongs between, and a
290 // full-screen triangle pair drawn with the blur or the composite material
291 const focus = front
292 ? (() => {
293 const options = { type: THREE.HalfFloatType, depthBuffer: true };
294 const a = new THREE.WebGLRenderTarget(1, 1, options);
295 const b = new THREE.WebGLRenderTarget(1, 1, { ...options, depthBuffer: false });
296 const blurMaterial = new THREE.ShaderMaterial({
297 uniforms: { tMap: { value: null }, uStep: { value: new THREE.Vector2() } },
298 vertexShader: quadVertexShader,
299 fragmentShader: blurFragmentShader,
300 depthTest: false,
301 depthWrite: false,
302 });
303 const compositeMaterial = new THREE.ShaderMaterial({
304 uniforms: { tMap: { value: null } },
305 vertexShader: quadVertexShader,
306 fragmentShader: compositeFragmentShader,
307 transparent: true,
308 depthTest: false,
309 depthWrite: false,
310 blending: THREE.CustomBlending,
311 blendSrc: THREE.OneFactor,
312 blendDst: THREE.OneMinusSrcAlphaFactor,
313 blendSrcAlpha: THREE.OneFactor,
314 blendDstAlpha: THREE.OneMinusSrcAlphaFactor,
315 });
316 const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), blurMaterial);
317 quad.frustumCulled = false;
318 const quadScene = new THREE.Scene();
319 quadScene.add(quad);
320 const quadCamera = new THREE.Camera();
321 return { a, b, blurMaterial, compositeMaterial, quad, quadScene, quadCamera };
322 })()
323 : null;
324
325 const draw = () => {
326 if (!focus) {
327 renderer.render(scene, camera);
328 return;
329 }
330 const { a, b, blurMaterial, compositeMaterial, quad, quadScene, quadCamera } = focus;
331 // 1. Out-of-focus shapes, small, on transparent black
332 camera.layers.set(1);
333 renderer.setRenderTarget(a);
334 renderer.setClearColor(BLACK, 0);
335 renderer.clear();
336 renderer.render(scene, camera);
337 // 2. Blur: horizontal then vertical, twice
338 quad.material = blurMaterial;
339 for (let i = 0; i < BLUR_ITERATIONS; i++) {
340 blurMaterial.uniforms.tMap.value = a.texture;
341 blurMaterial.uniforms.uStep.value.set(BLUR_SPREAD / a.width, 0);
342 renderer.setRenderTarget(b);
343 renderer.render(quadScene, quadCamera);
344 blurMaterial.uniforms.tMap.value = b.texture;
345 blurMaterial.uniforms.uStep.value.set(0, BLUR_SPREAD / a.height);
346 renderer.setRenderTarget(a);
347 renderer.render(quadScene, quadCamera);
348 }
349 // 3. Sharp shapes on the canvas, then the blurred ones over them (they are always closer)
350 renderer.setRenderTarget(null);
351 camera.layers.set(0);
352 renderer.render(scene, camera);
353 quad.material = compositeMaterial;
354 compositeMaterial.uniforms.tMap.value = a.texture;
355 renderer.autoClear = false;
356 renderer.render(quadScene, quadCamera);
357 renderer.autoClear = true;
358 };
359
360 const resize = () => {
361 // Foreground layer: size of its section; background: size of the viewport
362 const w = front ? canvas.parentElement.clientWidth : window.innerWidth;
363 const h = front ? canvas.parentElement.clientHeight : window.innerHeight;
364 renderer.setSize(w, h, false);
365 camera.aspect = w / h;
366 camera.updateProjectionMatrix();
367 if (focus) {
368 const ratio = renderer.getPixelRatio() * BLUR_SCALE;
369 const bw = Math.max(1, Math.round(w * ratio));
370 const bh = Math.max(1, Math.round(h * ratio));
371 focus.a.setSize(bw, bh);
372 focus.b.setSize(bw, bh);
373 }
374 if (reduced) draw();
375 };
376 const onScroll = () => {
377 if (front) {
378 // Foreground: progress over the first screen of scroll (the hero's pin), clamped
379 scrollTarget = Math.min(1, window.scrollY / window.innerHeight);
380 return;
381 }
382 const max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
383 scrollTarget = window.scrollY / max;
384 };
385 const onPointer = (event) => {
386 pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
387 pointer.y = (event.clientY / window.innerHeight) * 2 - 1;
388 };
389
390 let raf = 0;
391 let timer = null;
392 let announced = false;
393 const announceReady = () => {
394 if (announced) return;
395 announced = true;
396 onReadyRef.current?.();
397 };
398
399 // Foreground only: pause while its section is off screen, and stop drawing once the camera has
400 // flown past every shape (after the hero, the layer is empty)
401 let onScreen = true;
402 let cleared = false;
403 const visibility = front
404 ? new IntersectionObserver(([entry]) => {
405 onScreen = entry.isIntersecting;
406 })
407 : null;
408 visibility?.observe(canvas);
409 // Farthest shape from the resting camera (z decreases away from it)
410 const farthestZ = front ? Math.min(...data.map((s) => s.z)) : 0;
411
412 if (reduced) {
413 // Reduced motion: a single still frame, camera at rest, shapes frozen
414 camera.lookAt(0, 0, camera.position.z - 10);
415 place(0);
416 resize();
417 announceReady();
418 window.addEventListener("resize", resize);
419 } else {
420 resize();
421 onScroll();
422 window.addEventListener("resize", resize);
423 window.addEventListener("scroll", onScroll, { passive: true });
424 window.addEventListener("pointermove", onPointer, { passive: true });
425
426 timer = new THREE.Timer();
427 timer.connect(document); // pauses time while the tab is hidden
428
429 const frame = () => {
430 raf = requestAnimationFrame(frame);
431 if (document.hidden || !onScreen) return;
432 timer.update();
433 const t = timer.getElapsed();
434
435 // The camera travels through the cloud as the page scrolls, with some inertia
436 scrollCurrent += (scrollTarget - scrollCurrent) * 0.06;
437 pointer.sx += (pointer.x - pointer.sx) * 0.05;
438 pointer.sy += (pointer.y - pointer.sy) * 0.05;
439 // The foreground camera flies through its few shapes during the hero's pin, so they rush past the screen
440 camera.position.z = REST_Z - scrollCurrent * (front ? FRONT_TRAVEL : DEPTH - 20);
441 camera.position.x = pointer.sx * 1.2;
442 camera.position.y = -pointer.sy * 0.8;
443 camera.lookAt(pointer.sx * 0.6, -pointer.sy * 0.4, camera.position.z - 10);
444
445 if (front && camera.position.z < farthestZ - 1) {
446 if (!cleared) renderer.clear();
447 cleared = true;
448 announceReady();
449 return;
450 }
451 cleared = false;
452
453 place(t);
454 draw();
455 announceReady();
456 };
457 frame();
458 }
459
460 return () => {
461 cancelAnimationFrame(raf);
462 timer?.dispose();
463 visibility?.disconnect();
464 window.removeEventListener("resize", resize);
465 window.removeEventListener("scroll", onScroll);
466 window.removeEventListener("pointermove", onPointer);
467 meshes.forEach((mesh) => mesh.dispose());
468 blurMeshes?.forEach((mesh) => mesh.dispose());
469 blurredMaterial?.dispose();
470 if (focus) {
471 focus.a.dispose();
472 focus.b.dispose();
473 focus.blurMaterial.dispose();
474 focus.compositeMaterial.dispose();
475 focus.quad.geometry.dispose();
476 }
477 geometries.forEach((geometry) => geometry.dispose());
478 material.dispose();
479 envTarget.dispose();
480 renderer.dispose();
481 // dispose() keeps the WebGL context alive: release it now, or remounts (HMR, navigation) pile them up
482 renderer.forceContextLoss();
483 canvas.remove();
484 };
485 }, [front]);
486
487 return (
488 <div
489 ref={hostRef}
490 aria-hidden="true"
491 className={`pointer-events-none h-full w-full ${front ? "absolute inset-0" : "fixed inset-0 -z-10"}`}
492 />
493 );
494}
495
496const __ChromeField = ChromeField2;
497
498const ChromeField = load3D(() => Promise.resolve({ default: __ChromeField }));
499
500/**
501 * Chrome field used two ways at once:
502 * - without `front`: a fixed canvas behind the whole page; the camera flies through the cloud as you scroll;
503 * - with `front`: a transparent layer of a few large shapes, placed above the headline of one section.
504 */
505export default function ChromeFieldDemo() {
506 return (
507 <main className="relative isolate min-h-[300vh] bg-black text-white">
508 <ChromeField />
509
510 <section className="relative flex h-screen items-center justify-center overflow-hidden px-6">
511 <h1 className="relative z-10 text-center text-6xl font-bold leading-[0.9] tracking-tighter sm:text-8xl">
512 Chrome
513 <br />
514 field
515 </h1>
516 {/* Foreground layer: above the headline (z-15), sized to its section */}
517 <div aria-hidden="true" className="pointer-events-none absolute inset-0 z-[15]">
518 <ChromeField front />
519 </div>
520 </section>
521
522 <section className="relative flex h-[200vh] items-start justify-center px-6 pt-[40vh]">
523 <p className="max-w-lg text-center text-xl text-white/70">
524 Keep scrolling: the background camera travels through the cloud with a little inertia.
525 </p>
526 </section>
527 </main>
528 );
529}
03

Drop it in a page

It fills the box you put it in.

app/page.jsx
1import ChromeFieldDemo from "@/components/ChromeFieldDemo";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <ChromeFieldDemo />
8 </div>
9 );
10}
Next componentChrome Cube→