Glass prism 3D hero
A real glass prism floats in front of a giant word and bends it. Turn it to the right angle and white light splits into a rainbow.
"use client";
import { useEffect, useRef, useState, type CSSProperties } from "react";
import * as THREE from "three";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import "./prism-hero.css";
type PrismHeroProps = {
/** The giant word printed behind the glass (the glass refracts it). */
word?: string;
issue?: string;
title?: string;
text?: string;
cta?: { label: string; href: string };
/** The angle (0 to 119 degrees) where the light splits into a full rainbow. */
sweetSpot?: number;
};
const SERIF =
'"Bodoni 72", "Bodoni MT", Didot, "Playfair Display", Georgia, serif';
const BG = "#e6dfd1";
const INK = "#1d1a16";
const SPECTRUM = [
"#ff2e3a",
"#ff7a00",
"#ffd21f",
"#2fcf5b",
"#16b3ff",
"#3046ff",
"#9a3dff",
];
/**
* PrismHero
* - A real glass prism (three.js transmission + dispersion) floats in front of a giant word,
* so the glass bends the letters behind it.
* - Drag (or use the arrow keys) to turn it. Near the sweet spot the white beam splits into a
* rainbow fan and the caption changes; the dial on the right shows the angle.
* - Rendering pauses when the hero is off screen; reduced motion stops the idle spin and bob.
*/
export function PrismHero({
word = "Prism",
issue = "Issue 07",
title = "Seven colours were hiding in the white.",
text = "A quarterly journal about light: how we bend it, catch it and live by it. This issue is all about refraction.",
cta = { label: "Subscribe, €9 an issue", href: "#prism-subscribe" },
sweetSpot = 42,
}: PrismHeroProps) {
const rootRef = useRef<HTMLElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
const angleRef = useRef<HTMLSpanElement>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
const root = rootRef.current;
const stage = stageRef.current;
if (!root || !stage) return;
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true });
} catch {
const id = requestAnimationFrame(() => setFailed(true));
return () => cancelAnimationFrame(id);
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.toneMappingExposure = 1;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(BG);
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 60);
camera.position.set(0, 0, 10);
const pmrem = new THREE.PMREMGenerator(renderer);
const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
scene.environment = env;
/* ---- Backdrop: the big word, drawn on a canvas that fills the view ---- */
const BACK_Z = -3;
const typeCanvas = document.createElement("canvas");
const tctx = typeCanvas.getContext("2d")!;
const backMat = new THREE.MeshBasicMaterial({ toneMapped: false });
const backdrop = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), backMat);
backdrop.position.z = BACK_Z;
scene.add(backdrop);
/* ---- The prism ---- */
const glass = new THREE.MeshPhysicalMaterial({
color: 0xffffff,
roughness: 0,
transmission: 1,
thickness: 1.1,
ior: 1.5,
dispersion: 6,
clearcoat: 1,
clearcoatRoughness: 0.04,
attenuationColor: new THREE.Color("#f6f1ff"),
attenuationDistance: 24,
envMapIntensity: 0.6,
flatShading: true,
});
// A triangular prism lying along the view axis, so the visitor sees its triangle end.
const prismGeo = new THREE.CylinderGeometry(1.25, 1.25, 1.5, 3, 1);
prismGeo.rotateX(Math.PI / 2);
const prism = new THREE.Mesh(prismGeo, glass);
// Fine ink edges keep the glass crisp against the pale paper.
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(prismGeo),
new THREE.LineBasicMaterial({
color: INK,
transparent: true,
opacity: 0.35,
}),
);
prism.add(edges);
const pivot = new THREE.Group();
pivot.add(prism);
scene.add(pivot);
/* ---- Light: one white beam in, a fan of seven colours out ---- */
const fadeCanvas = document.createElement("canvas");
fadeCanvas.width = 256;
fadeCanvas.height = 8;
const fctx = fadeCanvas.getContext("2d")!;
const fade = fctx.createLinearGradient(0, 0, 256, 0);
fade.addColorStop(0, "rgba(255,255,255,1)");
fade.addColorStop(0.55, "rgba(255,255,255,.55)");
fade.addColorStop(1, "rgba(255,255,255,0)");
fctx.fillStyle = fade;
fctx.fillRect(0, 0, 256, 8);
const fadeTex = new THREE.CanvasTexture(fadeCanvas);
const rayGeo = new THREE.PlaneGeometry(1, 1);
rayGeo.translate(0.5, 0, 0);
const beam = new THREE.Mesh(
rayGeo,
new THREE.MeshBasicMaterial({
color: "#ffffff",
map: fadeTex,
transparent: true,
opacity: 0.95,
depthWrite: false,
toneMapped: false,
}),
);
beam.scale.set(10, 0.06, 1);
beam.rotation.z = Math.PI + 0.3;
const fan = new THREE.Group();
const rays = SPECTRUM.map((c) => {
const m = new THREE.Mesh(
rayGeo,
new THREE.MeshBasicMaterial({
color: c,
map: fadeTex,
transparent: true,
opacity: 0,
depthWrite: false,
toneMapped: false,
}),
);
fan.add(m);
return m;
});
scene.add(beam, fan);
/* ---- Layout: depends on the stage's shape ---- */
let width = 1;
let height = 1;
let prismX = 0;
let prismY = -0.55;
const drawBackdrop = () => {
const dist = camera.position.z - BACK_Z;
const vh =
2 * dist * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * 1.08;
const vw = vh * camera.aspect;
backdrop.scale.set(vw, vh, 1);
const s = Math.min(2048 / width, 2048 / height, 2);
const W = (typeCanvas.width = Math.max(2, Math.round(width * s)));
const H = (typeCanvas.height = Math.max(2, Math.round(height * s)));
tctx.fillStyle = BG;
tctx.fillRect(0, 0, W, H);
const glow = tctx.createRadialGradient(
W * 0.5,
H * 0.42,
0,
W * 0.5,
H * 0.5,
Math.max(W, H) * 0.7,
);
glow.addColorStop(0, "rgba(255,252,245,.75)");
glow.addColorStop(1, "rgba(255,252,245,0)");
tctx.fillStyle = glow;
tctx.fillRect(0, 0, W, H);
// The soft shadow under the prism, placed by projecting its base onto the screen.
const base = new THREE.Vector3(prismX, prismY - 1.25, 0).project(camera);
const sx = ((base.x + 1) / 2 - 0.5) / 1.08 + 0.5;
const sy = (1 - (base.y + 1) / 2 - 0.5) / 1.08 + 0.5;
const shadow = tctx.createRadialGradient(
sx * W,
sy * H,
0,
sx * W,
sy * H,
W * 0.16,
);
shadow.addColorStop(0, "rgba(40,30,20,.22)");
shadow.addColorStop(1, "rgba(40,30,20,0)");
tctx.save();
tctx.translate(sx * W, sy * H);
tctx.scale(1, 0.16);
tctx.translate(-sx * W, -sy * H);
tctx.fillStyle = shadow;
tctx.fillRect(0, 0, W, H);
tctx.restore();
// The word: as wide as the stage allows, sitting so the prism covers its lower half.
let size = H * 0.5;
tctx.font = `italic 400 ${size}px ${SERIF}`;
const m = tctx.measureText(word).width;
size = Math.min(size, (size * W * 0.92) / m);
tctx.font = `italic 400 ${size}px ${SERIF}`;
tctx.fillStyle = INK;
tctx.textAlign = "center";
tctx.textBaseline = "alphabetic";
tctx.fillText(
word,
W / 2,
H * (camera.aspect < 0.8 ? 0.3 : 0.36) + size * 0.36,
);
const old = backMat.map;
backMat.map = new THREE.CanvasTexture(typeCanvas);
backMat.map.colorSpace = THREE.SRGBColorSpace;
backMat.map.anisotropy = 4;
backMat.needsUpdate = true;
old?.dispose();
};
const resize = (w: number, h: number) => {
if (w < 2 || h < 2) return;
width = w;
height = h;
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.fov = camera.aspect < 0.8 ? 40 : 30;
camera.updateProjectionMatrix();
prismX = camera.aspect > 0.95 ? Math.min(1.9, camera.aspect * 1.05) : 0;
prismY = camera.aspect < 0.8 ? 0.2 : -0.55;
pivot.position.set(prismX, prismY, 0);
pivot.scale.setScalar(camera.aspect < 0.8 ? 0.72 : 0.85);
beam.position.set(prismX - 0.5, prismY + 0.05, 0.9);
fan.position.set(prismX + 0.5, prismY - 0.1, 0.9);
drawBackdrop();
};
let lastSize = "";
const ro = new ResizeObserver(([entry]) => {
const { width: w, height: h } = entry.contentRect;
const key = `${Math.round(w)}x${Math.round(h)}`;
if (key === lastSize) return;
lastSize = key;
resize(w, h);
});
ro.observe(stage);
/* ---- Input ---- */
let rotY = 0.35;
let rotX = 0.12;
let velY = 0;
let hx = 0;
let hy = 0;
let hxS = 0;
let hyS = 0;
let dragging = false;
let lastX = 0;
let lastY = 0;
let touched = -1e9;
const onDown = (e: PointerEvent) => {
dragging = true;
lastX = e.clientX;
lastY = e.clientY;
touched = performance.now();
stage.setPointerCapture?.(e.pointerId);
stage.dataset.dragging = "true";
};
const onMove = (e: PointerEvent) => {
const r = stage.getBoundingClientRect();
hx = ((e.clientX - r.left) / r.width) * 2 - 1;
hy = ((e.clientY - r.top) / r.height) * 2 - 1;
if (!dragging) return;
const dx = e.clientX - lastX;
const dy = e.clientY - lastY;
lastX = e.clientX;
lastY = e.clientY;
velY = (dx / r.width) * 4;
rotY += velY;
rotX = THREE.MathUtils.clamp(rotX + (dy / r.height) * 2, -0.5, 0.5);
touched = performance.now();
};
const onUp = () => {
dragging = false;
delete stage.dataset.dragging;
touched = performance.now();
};
const onLeave = () => {
hx = 0;
hy = 0;
};
const onKey = (e: KeyboardEvent) => {
const step = THREE.MathUtils.degToRad(e.shiftKey ? 10 : 3);
if (e.key === "ArrowLeft") rotY -= step;
else if (e.key === "ArrowRight") rotY += step;
else if (e.key === "ArrowUp") rotX = Math.max(-0.5, rotX - 0.05);
else if (e.key === "ArrowDown") rotX = Math.min(0.5, rotX + 0.05);
else return;
e.preventDefault();
velY = 0;
touched = performance.now();
};
stage.addEventListener("pointerdown", onDown);
stage.addEventListener("pointermove", onMove);
stage.addEventListener("pointerup", onUp);
stage.addEventListener("pointercancel", onUp);
stage.addEventListener("pointerleave", onLeave);
stage.addEventListener("keydown", onKey);
/* ---- Loop ---- */
let raf = 0;
let visible = true;
let glowS = 0;
let shown = -1;
const t0 = performance.now();
const loop = (now: number) => {
raf = 0;
if (!visible || document.hidden) return;
const t = (now - t0) / 1000;
if (!dragging) {
rotY += velY;
velY *= reduce ? 0 : 0.93;
if (!reduce && now - touched > 2600) rotY += 0.0024;
}
const ease = reduce ? 1 : 0.06;
hxS += (hx - hxS) * ease;
hyS += (hy - hyS) * ease;
const turn = rotY;
pivot.rotation.set(rotX + hyS * 0.12, -0.42 + hxS * 0.18, -turn);
prism.position.y = reduce ? 0 : Math.sin(t * 0.9) * 0.07;
const deg = ((THREE.MathUtils.radToDeg(turn) % 120) + 120) % 120;
const off = Math.min(
Math.abs(deg - sweetSpot),
120 - Math.abs(deg - sweetSpot),
);
const glow = Math.exp(-(off * off) / (2 * 9 * 9));
glowS += (glow - glowS) * (reduce ? 1 : 0.12);
const spread = 0.006 + glowS * 0.05;
const tilt = 0.26 + ((deg - sweetSpot) / 120) * 0.5;
rays.forEach((ray, i) => {
ray.rotation.z = tilt + (i - 3) * spread;
ray.scale.set(4 + glowS * 7, 0.035 + glowS * 0.05, 1);
(ray.material as THREE.MeshBasicMaterial).opacity = 0.04 + glowS * 0.9;
});
fan.position.y = prismY - 0.1 + prism.position.y;
beam.position.y = prismY + 0.05 + prism.position.y;
const rounded = Math.round(deg) % 120;
if (rounded !== shown) {
shown = rounded;
if (angleRef.current) angleRef.current.textContent = `${rounded}°`;
root.style.setProperty("--angle", `${deg * 3}deg`);
stage.setAttribute("aria-valuenow", String(rounded));
stage.setAttribute(
"aria-valuetext",
`${rounded} degrees${glowS > 0.55 ? ", the light splits into a rainbow" : ""}`,
);
}
root.dataset.lit = glowS > 0.55 ? "true" : "false";
renderer.render(scene, camera);
raf = requestAnimationFrame(loop);
};
const wake = () => {
if (!raf && visible && !document.hidden)
raf = requestAnimationFrame(loop);
};
const io = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting;
wake();
});
io.observe(stage);
document.addEventListener("visibilitychange", wake);
wake();
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
document.removeEventListener("visibilitychange", wake);
stage.removeEventListener("pointerdown", onDown);
stage.removeEventListener("pointermove", onMove);
stage.removeEventListener("pointerup", onUp);
stage.removeEventListener("pointercancel", onUp);
stage.removeEventListener("pointerleave", onLeave);
stage.removeEventListener("keydown", onKey);
scene.traverse((o) => {
if (o instanceof THREE.Mesh || o instanceof THREE.LineSegments) {
o.geometry.dispose();
const mat = o.material as THREE.MeshBasicMaterial;
mat.map?.dispose();
mat.dispose();
}
});
fadeTex.dispose();
env.dispose();
pmrem.dispose();
renderer.dispose();
renderer.forceContextLoss();
renderer.domElement.remove();
};
}, [word, sweetSpot]);
return (
<section
ref={rootRef}
className="gu-prism"
data-lit="false"
data-failed={failed || undefined}
aria-labelledby="gu-prism-title"
>
<div
ref={stageRef}
className="gu-prism__stage"
tabIndex={0}
role="slider"
aria-label="Turn the glass prism"
aria-valuemin={0}
aria-valuemax={119}
aria-valuenow={0}
/>
{failed && (
<div className="gu-prism__fallback" aria-hidden="true">
<span>{word}</span>
<i />
</div>
)}
<header className="gu-prism__bar">
<a className="gu-prism__mark" href="#">
{word}
<small>{issue}</small>
</a>
<nav aria-label="Main">
<a href="#prism-archive">Archive</a>
<a href="#prism-stockists">Stockists</a>
</nav>
</header>
<div className="gu-prism__copy">
<h1 id="gu-prism-title">{title}</h1>
<p>{text}</p>
<a className="gu-prism__cta" href={cta.href}>
{cta.label}
</a>
</div>
<div className="gu-prism__gauge" aria-hidden="true">
<div
className="gu-prism__dial"
style={{ "--sweet": `${sweetSpot * 3}deg` } as CSSProperties}
/>
<span className="gu-prism__deg" ref={angleRef}>
0°
</span>
<p className="gu-prism__hint">Drag the prism until the light splits.</p>
<p className="gu-prism__found">
There it is: white light, split in seven.
</p>
</div>
</section>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: Glass prism 3D hero
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A full-width hero for a print journal about light. A real glass prism (three.js) floats in front of a giant italic serif word ("Prism") and refracts it. Dragging the prism turns it; at one angle the white beam splits into a seven-colour fan.
## Layout and look
- Section min-height 720px, warm paper #e6dfd1, ink #1d1a16. One WebGL canvas fills the section; HTML sits on top with `pointer-events: none` except links.
- Top bar: italic serif wordmark + "Issue 07", two nav links, a hairline under it.
- Bottom left: serif h1 (~2.7rem), a muted paragraph, a dark pill button whose hover adds a red and blue edge, like split light.
- Bottom right: a 96px dial with a needle that turns with the prism and a rainbow arc marking the sweet spot, plus a hint that swaps for "There it is: white light, split in seven." when the light splits.
## The 3D scene
1. Perspective camera (fov 30, z 10), ACES tone mapping, RoomEnvironment through PMREM for reflections.
2. A backdrop plane at z -3 sized to fill the view. Its texture is a canvas the size of the stage: paper colour, a soft glow, a squashed shadow under the prism (placed by projecting the prism base) and the word fitted to 92% width. Redraw on resize.
3. Prism: CylinderGeometry with 3 radial segments, MeshPhysicalMaterial with transmission 1, thickness 1.8, ior 1.5, dispersion 6, clearcoat, flatShading. It sits right of centre on wide screens and centred on narrow ones.
4. Light: one white beam (a plane with a fading alpha texture) coming in from the upper left, and seven coloured rays fanning out to the right.
5. The angle is the prism's Y rotation modulo 120°. Glow = gaussian(distance to sweet spot, sigma 9°), eased. The glow drives the rays' opacity, length, thickness and spread.
## Behaviour
- Pointer drag turns the prism (horizontal) and tilts it (vertical, clamped) with inertia; it idles with a slow spin 2.6s after the last touch. The hover position adds a small lean.
- The stage is a focusable `role="slider"`: arrow keys turn it (Shift for bigger steps), with aria-valuenow and aria-valuetext kept up to date.
- Render loop pauses off screen (IntersectionObserver) and in hidden tabs. On unmount dispose everything and call `forceContextLoss()`.
- If WebGL is missing, show a CSS version of the cover: the word plus a frosted triangle.
## Reduced motion
No idle spin, bob, inertia or easing; it moves only when dragged or keyed.
## Props
word, issue, title, text, cta ({ label, href }), sweetSpot (degrees, 0–119).
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: three. Translate it faithfully; do not add new libraries unless my framework needs them.
### PrismHero.tsx
```tsx
"use client";
import { useEffect, useRef, useState, type CSSProperties } from "react";
import * as THREE from "three";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import "./prism-hero.css";
type PrismHeroProps = {
/** The giant word printed behind the glass (the glass refracts it). */
word?: string;
issue?: string;
title?: string;
text?: string;
cta?: { label: string; href: string };
/** The angle (0 to 119 degrees) where the light splits into a full rainbow. */
sweetSpot?: number;
};
const SERIF =
'"Bodoni 72", "Bodoni MT", Didot, "Playfair Display", Georgia, serif';
const BG = "#e6dfd1";
const INK = "#1d1a16";
const SPECTRUM = [
"#ff2e3a",
"#ff7a00",
"#ffd21f",
"#2fcf5b",
"#16b3ff",
"#3046ff",
"#9a3dff",
];
/**
* PrismHero
* - A real glass prism (three.js transmission + dispersion) floats in front of a giant word,
* so the glass bends the letters behind it.
* - Drag (or use the arrow keys) to turn it. Near the sweet spot the white beam splits into a
* rainbow fan and the caption changes; the dial on the right shows the angle.
* - Rendering pauses when the hero is off screen; reduced motion stops the idle spin and bob.
*/
export function PrismHero({
word = "Prism",
issue = "Issue 07",
title = "Seven colours were hiding in the white.",
text = "A quarterly journal about light: how we bend it, catch it and live by it. This issue is all about refraction.",
cta = { label: "Subscribe, €9 an issue", href: "#prism-subscribe" },
sweetSpot = 42,
}: PrismHeroProps) {
const rootRef = useRef<HTMLElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
const angleRef = useRef<HTMLSpanElement>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
const root = rootRef.current;
const stage = stageRef.current;
if (!root || !stage) return;
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true });
} catch {
const id = requestAnimationFrame(() => setFailed(true));
return () => cancelAnimationFrame(id);
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.toneMappingExposure = 1;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(BG);
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 60);
camera.position.set(0, 0, 10);
const pmrem = new THREE.PMREMGenerator(renderer);
const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
scene.environment = env;
/* ---- Backdrop: the big word, drawn on a canvas that fills the view ---- */
const BACK_Z = -3;
const typeCanvas = document.createElement("canvas");
const tctx = typeCanvas.getContext("2d")!;
const backMat = new THREE.MeshBasicMaterial({ toneMapped: false });
const backdrop = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), backMat);
backdrop.position.z = BACK_Z;
scene.add(backdrop);
/* ---- The prism ---- */
const glass = new THREE.MeshPhysicalMaterial({
color: 0xffffff,
roughness: 0,
transmission: 1,
thickness: 1.1,
ior: 1.5,
dispersion: 6,
clearcoat: 1,
clearcoatRoughness: 0.04,
attenuationColor: new THREE.Color("#f6f1ff"),
attenuationDistance: 24,
envMapIntensity: 0.6,
flatShading: true,
});
// A triangular prism lying along the view axis, so the visitor sees its triangle end.
const prismGeo = new THREE.CylinderGeometry(1.25, 1.25, 1.5, 3, 1);
prismGeo.rotateX(Math.PI / 2);
const prism = new THREE.Mesh(prismGeo, glass);
// Fine ink edges keep the glass crisp against the pale paper.
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(prismGeo),
new THREE.LineBasicMaterial({
color: INK,
transparent: true,
opacity: 0.35,
}),
);
prism.add(edges);
const pivot = new THREE.Group();
pivot.add(prism);
scene.add(pivot);
/* ---- Light: one white beam in, a fan of seven colours out ---- */
const fadeCanvas = document.createElement("canvas");
fadeCanvas.width = 256;
fadeCanvas.height = 8;
const fctx = fadeCanvas.getContext("2d")!;
const fade = fctx.createLinearGradient(0, 0, 256, 0);
fade.addColorStop(0, "rgba(255,255,255,1)");
fade.addColorStop(0.55, "rgba(255,255,255,.55)");
fade.addColorStop(1, "rgba(255,255,255,0)");
fctx.fillStyle = fade;
fctx.fillRect(0, 0, 256, 8);
const fadeTex = new THREE.CanvasTexture(fadeCanvas);
const rayGeo = new THREE.PlaneGeometry(1, 1);
rayGeo.translate(0.5, 0, 0);
const beam = new THREE.Mesh(
rayGeo,
new THREE.MeshBasicMaterial({
color: "#ffffff",
map: fadeTex,
transparent: true,
opacity: 0.95,
depthWrite: false,
toneMapped: false,
}),
);
beam.scale.set(10, 0.06, 1);
beam.rotation.z = Math.PI + 0.3;
const fan = new THREE.Group();
const rays = SPECTRUM.map((c) => {
const m = new THREE.Mesh(
rayGeo,
new THREE.MeshBasicMaterial({
color: c,
map: fadeTex,
transparent: true,
opacity: 0,
depthWrite: false,
toneMapped: false,
}),
);
fan.add(m);
return m;
});
scene.add(beam, fan);
/* ---- Layout: depends on the stage's shape ---- */
let width = 1;
let height = 1;
let prismX = 0;
let prismY = -0.55;
const drawBackdrop = () => {
const dist = camera.position.z - BACK_Z;
const vh =
2 * dist * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * 1.08;
const vw = vh * camera.aspect;
backdrop.scale.set(vw, vh, 1);
const s = Math.min(2048 / width, 2048 / height, 2);
const W = (typeCanvas.width = Math.max(2, Math.round(width * s)));
const H = (typeCanvas.height = Math.max(2, Math.round(height * s)));
tctx.fillStyle = BG;
tctx.fillRect(0, 0, W, H);
const glow = tctx.createRadialGradient(
W * 0.5,
H * 0.42,
0,
W * 0.5,
H * 0.5,
Math.max(W, H) * 0.7,
);
glow.addColorStop(0, "rgba(255,252,245,.75)");
glow.addColorStop(1, "rgba(255,252,245,0)");
tctx.fillStyle = glow;
tctx.fillRect(0, 0, W, H);
// The soft shadow under the prism, placed by projecting its base onto the screen.
const base = new THREE.Vector3(prismX, prismY - 1.25, 0).project(camera);
const sx = ((base.x + 1) / 2 - 0.5) / 1.08 + 0.5;
const sy = (1 - (base.y + 1) / 2 - 0.5) / 1.08 + 0.5;
const shadow = tctx.createRadialGradient(
sx * W,
sy * H,
0,
sx * W,
sy * H,
W * 0.16,
);
shadow.addColorStop(0, "rgba(40,30,20,.22)");
shadow.addColorStop(1, "rgba(40,30,20,0)");
tctx.save();
tctx.translate(sx * W, sy * H);
tctx.scale(1, 0.16);
tctx.translate(-sx * W, -sy * H);
tctx.fillStyle = shadow;
tctx.fillRect(0, 0, W, H);
tctx.restore();
// The word: as wide as the stage allows, sitting so the prism covers its lower half.
let size = H * 0.5;
tctx.font = `italic 400 ${size}px ${SERIF}`;
const m = tctx.measureText(word).width;
size = Math.min(size, (size * W * 0.92) / m);
tctx.font = `italic 400 ${size}px ${SERIF}`;
tctx.fillStyle = INK;
tctx.textAlign = "center";
tctx.textBaseline = "alphabetic";
tctx.fillText(
word,
W / 2,
H * (camera.aspect < 0.8 ? 0.3 : 0.36) + size * 0.36,
);
const old = backMat.map;
backMat.map = new THREE.CanvasTexture(typeCanvas);
backMat.map.colorSpace = THREE.SRGBColorSpace;
backMat.map.anisotropy = 4;
backMat.needsUpdate = true;
old?.dispose();
};
const resize = (w: number, h: number) => {
if (w < 2 || h < 2) return;
width = w;
height = h;
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.fov = camera.aspect < 0.8 ? 40 : 30;
camera.updateProjectionMatrix();
prismX = camera.aspect > 0.95 ? Math.min(1.9, camera.aspect * 1.05) : 0;
prismY = camera.aspect < 0.8 ? 0.2 : -0.55;
pivot.position.set(prismX, prismY, 0);
pivot.scale.setScalar(camera.aspect < 0.8 ? 0.72 : 0.85);
beam.position.set(prismX - 0.5, prismY + 0.05, 0.9);
fan.position.set(prismX + 0.5, prismY - 0.1, 0.9);
drawBackdrop();
};
let lastSize = "";
const ro = new ResizeObserver(([entry]) => {
const { width: w, height: h } = entry.contentRect;
const key = `${Math.round(w)}x${Math.round(h)}`;
if (key === lastSize) return;
lastSize = key;
resize(w, h);
});
ro.observe(stage);
/* ---- Input ---- */
let rotY = 0.35;
let rotX = 0.12;
let velY = 0;
let hx = 0;
let hy = 0;
let hxS = 0;
let hyS = 0;
let dragging = false;
let lastX = 0;
let lastY = 0;
let touched = -1e9;
const onDown = (e: PointerEvent) => {
dragging = true;
lastX = e.clientX;
lastY = e.clientY;
touched = performance.now();
stage.setPointerCapture?.(e.pointerId);
stage.dataset.dragging = "true";
};
const onMove = (e: PointerEvent) => {
const r = stage.getBoundingClientRect();
hx = ((e.clientX - r.left) / r.width) * 2 - 1;
hy = ((e.clientY - r.top) / r.height) * 2 - 1;
if (!dragging) return;
const dx = e.clientX - lastX;
const dy = e.clientY - lastY;
lastX = e.clientX;
lastY = e.clientY;
velY = (dx / r.width) * 4;
rotY += velY;
rotX = THREE.MathUtils.clamp(rotX + (dy / r.height) * 2, -0.5, 0.5);
touched = performance.now();
};
const onUp = () => {
dragging = false;
delete stage.dataset.dragging;
touched = performance.now();
};
const onLeave = () => {
hx = 0;
hy = 0;
};
const onKey = (e: KeyboardEvent) => {
const step = THREE.MathUtils.degToRad(e.shiftKey ? 10 : 3);
if (e.key === "ArrowLeft") rotY -= step;
else if (e.key === "ArrowRight") rotY += step;
else if (e.key === "ArrowUp") rotX = Math.max(-0.5, rotX - 0.05);
else if (e.key === "ArrowDown") rotX = Math.min(0.5, rotX + 0.05);
else return;
e.preventDefault();
velY = 0;
touched = performance.now();
};
stage.addEventListener("pointerdown", onDown);
stage.addEventListener("pointermove", onMove);
stage.addEventListener("pointerup", onUp);
stage.addEventListener("pointercancel", onUp);
stage.addEventListener("pointerleave", onLeave);
stage.addEventListener("keydown", onKey);
/* ---- Loop ---- */
let raf = 0;
let visible = true;
let glowS = 0;
let shown = -1;
const t0 = performance.now();
const loop = (now: number) => {
raf = 0;
if (!visible || document.hidden) return;
const t = (now - t0) / 1000;
if (!dragging) {
rotY += velY;
velY *= reduce ? 0 : 0.93;
if (!reduce && now - touched > 2600) rotY += 0.0024;
}
const ease = reduce ? 1 : 0.06;
hxS += (hx - hxS) * ease;
hyS += (hy - hyS) * ease;
const turn = rotY;
pivot.rotation.set(rotX + hyS * 0.12, -0.42 + hxS * 0.18, -turn);
prism.position.y = reduce ? 0 : Math.sin(t * 0.9) * 0.07;
const deg = ((THREE.MathUtils.radToDeg(turn) % 120) + 120) % 120;
const off = Math.min(
Math.abs(deg - sweetSpot),
120 - Math.abs(deg - sweetSpot),
);
const glow = Math.exp(-(off * off) / (2 * 9 * 9));
glowS += (glow - glowS) * (reduce ? 1 : 0.12);
const spread = 0.006 + glowS * 0.05;
const tilt = 0.26 + ((deg - sweetSpot) / 120) * 0.5;
rays.forEach((ray, i) => {
ray.rotation.z = tilt + (i - 3) * spread;
ray.scale.set(4 + glowS * 7, 0.035 + glowS * 0.05, 1);
(ray.material as THREE.MeshBasicMaterial).opacity = 0.04 + glowS * 0.9;
});
fan.position.y = prismY - 0.1 + prism.position.y;
beam.position.y = prismY + 0.05 + prism.position.y;
const rounded = Math.round(deg) % 120;
if (rounded !== shown) {
shown = rounded;
if (angleRef.current) angleRef.current.textContent = `${rounded}°`;
root.style.setProperty("--angle", `${deg * 3}deg`);
stage.setAttribute("aria-valuenow", String(rounded));
stage.setAttribute(
"aria-valuetext",
`${rounded} degrees${glowS > 0.55 ? ", the light splits into a rainbow" : ""}`,
);
}
root.dataset.lit = glowS > 0.55 ? "true" : "false";
renderer.render(scene, camera);
raf = requestAnimationFrame(loop);
};
const wake = () => {
if (!raf && visible && !document.hidden)
raf = requestAnimationFrame(loop);
};
const io = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting;
wake();
});
io.observe(stage);
document.addEventListener("visibilitychange", wake);
wake();
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
document.removeEventListener("visibilitychange", wake);
stage.removeEventListener("pointerdown", onDown);
stage.removeEventListener("pointermove", onMove);
stage.removeEventListener("pointerup", onUp);
stage.removeEventListener("pointercancel", onUp);
stage.removeEventListener("pointerleave", onLeave);
stage.removeEventListener("keydown", onKey);
scene.traverse((o) => {
if (o instanceof THREE.Mesh || o instanceof THREE.LineSegments) {
o.geometry.dispose();
const mat = o.material as THREE.MeshBasicMaterial;
mat.map?.dispose();
mat.dispose();
}
});
fadeTex.dispose();
env.dispose();
pmrem.dispose();
renderer.dispose();
renderer.forceContextLoss();
renderer.domElement.remove();
};
}, [word, sweetSpot]);
return (
<section
ref={rootRef}
className="gu-prism"
data-lit="false"
data-failed={failed || undefined}
aria-labelledby="gu-prism-title"
>
<div
ref={stageRef}
className="gu-prism__stage"
tabIndex={0}
role="slider"
aria-label="Turn the glass prism"
aria-valuemin={0}
aria-valuemax={119}
aria-valuenow={0}
/>
{failed && (
<div className="gu-prism__fallback" aria-hidden="true">
<span>{word}</span>
<i />
</div>
)}
<header className="gu-prism__bar">
<a className="gu-prism__mark" href="#">
{word}
<small>{issue}</small>
</a>
<nav aria-label="Main">
<a href="#prism-archive">Archive</a>
<a href="#prism-stockists">Stockists</a>
</nav>
</header>
<div className="gu-prism__copy">
<h1 id="gu-prism-title">{title}</h1>
<p>{text}</p>
<a className="gu-prism__cta" href={cta.href}>
{cta.label}
</a>
</div>
<div className="gu-prism__gauge" aria-hidden="true">
<div
className="gu-prism__dial"
style={{ "--sweet": `${sweetSpot * 3}deg` } as CSSProperties}
/>
<span className="gu-prism__deg" ref={angleRef}>
0°
</span>
<p className="gu-prism__hint">Drag the prism until the light splits.</p>
<p className="gu-prism__found">
There it is: white light, split in seven.
</p>
</div>
</section>
);
}
```
### prism-hero.css
```css
/* Prism: a printed journal cover that you can turn in your hand. */
.gu-prism {
--bg: #e6dfd1;
--ink: #1d1a16;
--muted: #5f574c;
--line: rgb(29 26 22 / 0.18);
--signal: #ff5a1f;
--focus: #2b35ff;
--ease: cubic-bezier(0.22, 1, 0.36, 1);
--serif: "Bodoni 72", "Bodoni MT", Didot, "Playfair Display", Georgia, serif;
--angle: 0deg;
position: relative;
container-type: inline-size;
min-height: 720px;
overflow: hidden;
isolation: isolate;
background: var(--bg);
color: var(--ink);
font-family:
system-ui,
-apple-system,
"Segoe UI",
sans-serif;
line-height: 1.5;
}
.gu-prism *,
.gu-prism *::before,
.gu-prism *::after {
box-sizing: border-box;
}
.gu-prism a {
color: inherit;
}
.gu-prism :focus-visible {
outline: 3px solid var(--focus);
outline-offset: 3px;
}
/* The WebGL stage fills the hero; the copy floats above it but lets drags through. */
.gu-prism__stage {
position: absolute;
inset: 0;
z-index: 0;
cursor: grab;
touch-action: pan-y;
}
.gu-prism__stage[data-dragging] {
cursor: grabbing;
}
.gu-prism__stage canvas {
display: block;
width: 100%;
height: 100%;
}
.gu-prism__stage:focus-visible {
outline-offset: -6px;
}
.gu-prism__bar,
.gu-prism__copy,
.gu-prism__gauge {
position: absolute;
z-index: 1;
pointer-events: none;
}
.gu-prism__bar a,
.gu-prism__cta {
pointer-events: auto;
}
.gu-prism__bar {
inset: 0 0 auto;
display: flex;
align-items: baseline;
justify-content: space-between;
padding: 26px 5%;
border-bottom: 1px solid var(--line);
}
.gu-prism__mark {
display: inline-flex;
align-items: baseline;
gap: 12px;
font-family: var(--serif);
font-size: 1.6rem;
font-style: italic;
text-decoration: none;
}
.gu-prism__mark small {
font-family:
system-ui,
-apple-system,
"Segoe UI",
sans-serif;
font-size: 0.8rem;
font-style: normal;
color: var(--muted);
}
.gu-prism__bar nav {
display: flex;
gap: 26px;
font-size: 0.92rem;
}
.gu-prism__bar nav a {
text-decoration: none;
background: linear-gradient(currentColor, currentColor) 0 100% / 0 1px
no-repeat;
transition: background-size 0.4s var(--ease);
}
.gu-prism__bar nav a:hover {
background-size: 100% 1px;
}
.gu-prism__copy {
left: 5%;
bottom: 56px;
max-width: min(440px, 42cqi);
animation: gu-prism-rise 1.1s var(--ease) 0.2s both;
}
.gu-prism__copy h1 {
margin: 0 0 14px;
font-family: var(--serif);
font-size: clamp(1.8rem, 3.4cqi, 2.7rem);
font-weight: 400;
line-height: 1.05;
letter-spacing: -0.01em;
text-wrap: balance;
}
.gu-prism__copy p {
margin: 0 0 24px;
color: var(--muted);
max-width: 38ch;
}
.gu-prism__cta {
display: inline-flex;
align-items: center;
min-height: 48px;
padding: 0 24px;
border-radius: 999px;
background: var(--ink);
color: var(--bg) !important;
font-weight: 650;
text-decoration: none;
transition:
transform 0.4s var(--ease),
box-shadow 0.4s var(--ease);
}
.gu-prism__cta:hover {
transform: translateY(-2px);
box-shadow:
0 14px 30px -14px rgb(29 26 22 / 0.6),
-6px 0 0 -2px #ff2e3a,
6px 0 0 -2px #3046ff;
}
/* The angle dial: a needle turns with the glass; the tick marks the sweet spot. */
.gu-prism__gauge {
right: 5%;
bottom: 56px;
display: grid;
justify-items: end;
gap: 10px;
text-align: right;
animation: gu-prism-rise 1.1s var(--ease) 0.35s both;
}
.gu-prism__dial {
position: relative;
display: grid;
place-items: center;
width: 96px;
aspect-ratio: 1;
border: 1px solid var(--line);
border-radius: 50%;
background: conic-gradient(
from calc(var(--sweet) - 18deg),
#ff2e3a,
#ff7a00,
#ffd21f,
#2fcf5b,
#16b3ff,
#3046ff,
#9a3dff 36deg,
rgb(255 252 245 / 0.55) 0
);
}
.gu-prism__dial::before {
content: "";
position: absolute;
inset: 8px;
border-radius: 50%;
background: var(--bg);
}
.gu-prism__dial::after {
content: "";
position: absolute;
left: calc(50% - 1px);
top: 10px;
width: 2px;
height: 38px;
border-radius: 2px;
background: var(--ink);
transform-origin: 50% 38px;
transform: rotate(var(--angle));
}
.gu-prism__deg {
font-variant-numeric: tabular-nums;
font-size: 1.6rem;
font-family: var(--serif);
line-height: 1;
}
.gu-prism__hint,
.gu-prism__found {
grid-area: 3 / 1;
margin: 0;
max-width: 24ch;
font-size: 0.92rem;
color: var(--muted);
transition:
opacity 0.5s var(--ease),
transform 0.5s var(--ease);
}
.gu-prism__found {
font-family: var(--serif);
font-size: 1.15rem;
font-style: italic;
color: var(--ink);
opacity: 0;
transform: translateY(8px);
}
.gu-prism[data-lit="true"] .gu-prism__hint {
opacity: 0;
transform: translateY(-8px);
}
.gu-prism[data-lit="true"] .gu-prism__found {
opacity: 1;
transform: none;
}
@keyframes gu-prism-rise {
from {
opacity: 0;
transform: translateY(18px);
}
}
/* No WebGL: a printed version of the same cover. */
.gu-prism__fallback {
position: absolute;
inset: 0;
display: grid;
place-items: center;
}
.gu-prism__fallback span {
font-family: var(--serif);
font-style: italic;
font-size: 30cqi;
line-height: 1;
transform: translateY(-14%);
}
.gu-prism__fallback i {
position: absolute;
width: 26cqi;
aspect-ratio: 1 / 0.9;
clip-path: polygon(50% 0, 100% 100%, 0 100%);
background: linear-gradient(
160deg,
rgb(255 255 255 / 0.75),
rgb(255 255 255 / 0.2)
);
backdrop-filter: blur(6px);
}
@container (max-width: 720px) {
.gu-prism__bar nav {
display: none;
}
.gu-prism__copy {
right: 5%;
bottom: 32px;
max-width: none;
}
.gu-prism__gauge {
top: 84px;
bottom: auto;
grid-template-columns: auto auto;
align-items: center;
}
.gu-prism__hint,
.gu-prism__found {
display: none;
}
.gu-prism__dial {
width: 52px;
}
.gu-prism__dial::before {
inset: 5px;
}
.gu-prism__dial::after {
top: 6px;
height: 20px;
transform-origin: 50% 20px;
}
.gu-prism__deg {
grid-row: 1;
font-size: 1.2rem;
}
}
@media (prefers-reduced-motion: reduce) {
.gu-prism__copy,
.gu-prism__gauge {
animation: none;
}
.gu-prism__hint,
.gu-prism__found,
.gu-prism__cta {
transition: none;
}
}
```
You might also want
Next piece: Glossy toys physics 3D heroContour map 3D hero
Components, advanced, needs three
Glossy toys physics 3D hero
Components, advanced, needs three
Liquid blob album 3D hero
Components, advanced, needs three