Animations107 / 118
Prism Cube
A block of dichroic glass tumbling in the dark, full of coloured light. Its glass is traced in the shader, bouncing each ray off the inside walls with real dispersion. It leans toward your cursor and tumbles with momentum when you drag it; click and it cracks into eight glass cubes that burst apart, tumble and snap back together with a clack.
three.jsthree.jsRay-traced glassRay-traced glassDispersionDispersionSpringsSpringsGSAPGSAP
Drag to tumble itClick to crack it open
Tweak
LIVELIVELight
Panels
Glass
1.00
Motion
1.0×
Usage
Follows your tweaks.
usage.tsx
import { PrismCube } from "@/components/inreact/prism-cube";
export function Hero() {
return (
<section className="h-[640px] bg-black">
<PrismCube palette="neon" dispersion={1} speed={1} />
</section>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/prism-cube.jsonOr copy the source
Install the dependencies, then save this as components/inreact/prism-cube.tsx.
terminal
npm install gsap threecomponents/inreact/prism-cube.tsx
"use client";
import { gsap } from "gsap";
import { useEffect, useRef } from "react";
import * as THREE from "three";
import { RoundedBoxGeometry } from "three/addons/geometries/RoundedBoxGeometry.js";
/**
* Prism Cube: a block of dichroic glass tumbling in the dark, full of coloured light,
* rendered live in three.js.
*
* - The glass is traced for real: each pixel follows its ray into the cube, bounces it off the
* inside walls, and bends it out again, with red, green and blue bent by their own index.
* The coloured blocks you see inside are light panels, refracted and reflected.
* - It leans toward the cursor; drag to tumble it, and it coasts on with real momentum.
* - Click (or Enter / Space): it squeezes, then cracks into eight smaller cubes that burst apart,
* tumble, and snap back together with a clack and a squash.
*
* <div className="h-[600px] bg-black"><PrismCube /></div>
*/
export type PrismPalette = "neon" | "aurora" | "sunset";
export type PrismCubeProps = {
/** Colours of the light panels the glass refracts. */
palette?: PrismPalette;
/** How far red, green and blue split, 0 to 2. */
dispersion?: number;
/** Speed of the idle tumble (0 = still, 1 = default). */
speed?: number;
/** Background colour. */
background?: string;
/** Called when the cube cracks open. */
onBurst?: () => void;
className?: string;
};
const PALETTES: Record<PrismPalette, [number, number, number, number]> = {
neon: [0xff2fa8, 0x2b4dff, 0xffe14a, 0x5df2ff],
aurora: [0x29f0b4, 0x4a5cff, 0xb36bff, 0xe8fbff],
sunset: [0xff4d2e, 0xff2f8a, 0xffc23d, 0x6a5cff],
};
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const VERT = /* glsl */ `
varying vec3 vOP; // position in the cube's own space
varying vec3 vON; // normal in the cube's own space
varying vec3 vCamO; // the camera, in the cube's own space
varying vec3 vM0; // the cube's rotation, to turn rays back into world space
varying vec3 vM1;
varying vec3 vM2;
void main(){
mat3 m = mat3(modelMatrix);
vM0 = m[0]; vM1 = m[1]; vM2 = m[2];
vOP = position;
vON = normal;
vCamO = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}`;
const FRAG = /* glsl */ `
uniform samplerCube uEnv;
uniform float uHalf; // half the cube's size
uniform float uFire;
uniform float uFlash;
varying vec3 vOP;
varying vec3 vON;
varying vec3 vCamO;
varying vec3 vM0;
varying vec3 vM1;
varying vec3 vM2;
vec3 envAt(vec3 dirO){
vec3 d = normalize(mat3(vM0, vM1, vM2) * dirO); // back to world space
return textureLod(uEnv, d, 0.6).rgb;
}
// follow one colour's ray through the glass: in, up to three bounces off the inside walls, out
vec3 trace(vec3 p, vec3 v, vec3 n, float ior){
vec3 d = refract(v, n, 1.0 / ior);
vec3 tint = vec3(1.0);
for (int b = 0; b < 3; b++) {
vec3 tt = (sign(d) * uHalf - p) / d; // distance to each wall ahead
float t = min(tt.x, min(tt.y, tt.z));
p += d * t;
vec3 nOut = vec3(0.0);
if (t == tt.x) nOut.x = sign(d.x); else if (t == tt.y) nOut.y = sign(d.y); else nOut.z = sign(d.z);
vec3 o = refract(d, -nOut, ior);
if (dot(o, o) > 0.001) return envAt(o) * tint;
d = reflect(d, -nOut); // total internal reflection: it stays inside
tint *= 0.9;
}
return envAt(d) * tint * 0.6;
}
void main(){
vec3 v = normalize(vOP - vCamO);
vec3 n = normalize(vON);
float cosT = clamp(dot(-v, n), 0.0, 1.0);
float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0);
vec3 refl = envAt(reflect(v, n));
vec3 p = clamp(vOP, vec3(-uHalf * 0.999), vec3(uHalf * 0.999));
vec3 body;
body.r = trace(p, v, n, 1.50 - 0.03 * uFire).r;
body.g = trace(p, v, n, 1.50).g;
body.b = trace(p, v, n, 1.50 + 0.03 * uFire).b;
vec3 c = mix(body, refl, F) * (1.0 + 0.5 * uFlash);
gl_FragColor = vec4(c, 1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`;
export function PrismCube({ palette = "neon", dispersion = 1, speed = 1, background = "#000000", onBurst, className }: PrismCubeProps) {
const rootRef = useRef<HTMLDivElement>(null);
const live = useRef({ dispersion, speed, onBurst });
live.current = { dispersion, speed, onBurst };
useEffect(() => {
const root = rootRef.current;
if (!root) return;
const still = reduced();
const [cA, cB, cC, cD] = (PALETTES[palette] ?? PALETTES.neon).map((h) => new THREE.Color(h));
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:block;";
root.appendChild(canvas);
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false, powerPreference: "high-performance" });
} catch {
canvas.remove();
return;
}
const dpr = Math.min(2, Math.max(1.25, window.devicePixelRatio || 1));
renderer.setPixelRatio(dpr);
renderer.setClearColor(new THREE.Color(background), 1);
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
// the light box: black, with hard-edged rectangular panels of saturated colour and white strips
const pmrem = new THREE.PMREMGenerator(renderer);
const studio = new THREE.Scene();
const envMat = new THREE.ShaderMaterial({
side: THREE.BackSide,
uniforms: { uA: { value: cA }, uB: { value: cB }, uC: { value: cC }, uD: { value: cD } },
vertexShader: "varying vec3 vD;\nvoid main(){ vD = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",
fragmentShader: `
varying vec3 vD;
uniform vec3 uA, uB, uC, uD;
// a rectangle of light on the sphere, centred on direction c, with half-sizes w x h (radians)
float rect(vec3 d, vec3 c, vec3 up, float w, float h){
c = normalize(c);
vec3 r = normalize(cross(up, c));
vec3 u = cross(c, r);
float fwd = dot(d, c);
if (fwd <= 0.0) return 0.0;
vec2 q = vec2(dot(d, r), dot(d, u)) / fwd;
vec2 e = abs(q) - vec2(w, h);
return 1.0 - smoothstep(-0.01, 0.01, max(e.x, e.y));
}
void main(){
vec3 d = normalize(vD);
vec3 Y = vec3(0.0, 1.0, 0.0);
vec3 c = vec3(0.0);
// a scattered light box: many smaller panels of colour and thin white strips, so the glass
// breaks the light into blocks and stripes instead of whole flat faces
c += vec3(0.02, 0.02, 0.03);
for (int i = 0; i < 44; i++) {
float fi = float(i);
// spread evenly over the sphere (a golden-angle spiral), so every view sees several panels
float zz = 1.0 - 2.0 * (fi + 0.5) / 44.0;
float rr = sqrt(1.0 - zz * zz);
vec3 dir = normalize(vec3(cos(fi * 2.39996) * rr, zz, sin(fi * 2.39996) * rr));
vec3 up = abs(dir.y) > 0.9 ? vec3(0.0, 0.0, 1.0) : Y;
float k = fract(sin(fi * 12.9898) * 43758.5453);
float w = 0.1 + 0.18 * fract(k * 7.1), h = 0.08 + 0.22 * fract(k * 3.7);
vec3 col = k < 0.22 ? uA : k < 0.4 ? uB : k < 0.52 ? uC : k < 0.62 ? uD : vec3(1.0);
if (k >= 0.62) { w *= 0.22; } // the white ones are thin strips
c = max(c, col * rect(d, dir, up, w, h) * (k >= 0.62 ? 3.2 : 2.2)); // overlaps keep their colour
}
gl_FragColor = vec4(c, 1.0);
}`,
});
const envSphere = new THREE.Mesh(new THREE.SphereGeometry(10, 96, 48), envMat);
studio.add(envSphere);
const env = pmrem.fromScene(studio, 0).texture;
envSphere.geometry.dispose();
envMat.dispose();
const makeMat = (half: number) =>
new THREE.ShaderMaterial({
uniforms: { uEnv: { value: env }, uHalf: { value: half }, uFire: { value: live.current.dispersion }, uFlash: { value: 0 } },
vertexShader: VERT,
fragmentShader: FRAG,
});
// the whole cube, and the eight pieces it cracks into
const S = 1.25;
const wholeGeo = new RoundedBoxGeometry(S, S, S, 8, S * 0.11);
const wholeMat = makeMat(S / 2);
const whole = new THREE.Mesh(wholeGeo, wholeMat);
const pieceGeo = new RoundedBoxGeometry(S / 2, S / 2, S / 2, 6, S * 0.07);
const pieceMat = makeMat(S / 4);
const pieces: { mesh: THREE.Mesh; dir: THREE.Vector3; axis: THREE.Vector3 }[] = [];
const piecesG = new THREE.Group();
for (const x of [-1, 1])
for (const y of [-1, 1])
for (const z of [-1, 1]) {
const mesh = new THREE.Mesh(pieceGeo, pieceMat);
const dir = new THREE.Vector3(x, y, z);
mesh.position.copy(dir).multiplyScalar(S / 4);
piecesG.add(mesh);
pieces.push({ mesh, dir, axis: new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize() });
}
piecesG.visible = false;
const spin = new THREE.Group(); // tumble
const squashG = new THREE.Group(); // squash and stretch
const lean = new THREE.Group(); // leans toward the cursor
spin.add(whole, piecesG);
squashG.add(spin);
lean.add(squashG);
scene.add(lean);
spin.quaternion.setFromEuler(new THREE.Euler(0.6, 0.75, 0.2));
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 100);
let W = 0, H = 0;
const resize = () => {
const w = root.clientWidth, h = root.clientHeight;
if (w < 2 || h < 2 || (w === W && h === H)) return;
W = w;
H = h;
renderer.setSize(W, H, false);
camera.aspect = W / H;
const span = 3.6;
const t = Math.tan(THREE.MathUtils.degToRad(15));
camera.position.set(0, 0, Math.max(span / (2 * t), span / (2 * t * camera.aspect)));
camera.lookAt(0, 0, 0);
camera.updateProjectionMatrix();
};
resize();
const ro = new ResizeObserver(resize);
ro.observe(root);
// ---- motion ----
type Spring = { x: number; v: number; t: number; k: number; c: number };
const sp = (x: number, k: number, c: number): Spring => ({ x, v: 0, t: x, k, c });
const step = (s: Spring, dt: number) => {
const h = dt / 2;
for (let i = 0; i < 2; i++) {
s.v += (s.k * (s.t - s.x) - s.c * s.v) * h;
s.x += s.v * h;
}
};
const leanX = sp(0, 36, 8.5), leanY = sp(0, 36, 8.5);
const squash = sp(1, 200, 9);
const burstAmt = sp(0, 90, 9); // 0 = whole, 1 = burst apart (overshoots on the way out)
const twist = sp(0, 60, 8);
const w = new THREE.Vector3(0.25, 0.4, 0.1); // angular velocity (world, rad/s)
const idleW = new THREE.Vector3(0.22, 0.38, 0.08);
const dragW = new THREE.Vector3();
const dq = new THREE.Quaternion(), qp = new THREE.Quaternion(), tmp = new THREE.Vector3();
let flash = 0, flashGoal = 0;
let pointer: { x: number; y: number } | null = null;
let drag: { x: number; y: number; t: number; sx: number; sy: number; t0: number; id: number } | null = null;
let busy = false, closing = false;
const calls: gsap.core.Tween[] = [];
let t = 0;
const burst = () => {
if (busy) return;
busy = true;
live.current.onBurst?.();
if (still) {
flashGoal = 1;
calls.push(gsap.delayedCall(0.4, () => (busy = false)));
return;
}
// anticipation: it squeezes
squash.t = 0.88;
calls.push(
gsap.delayedCall(0.13, () => {
// crack: swap the whole cube for its eight pieces (they sit exactly where it was), and burst
whole.visible = false;
piecesG.visible = true;
pieces.forEach((p) => p.axis.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize());
squash.t = 1;
squash.v += 2.2;
burstAmt.t = 1;
twist.t = 1;
flashGoal = 1;
w.multiplyScalar(0.4);
}),
gsap.delayedCall(1.25, () => {
// and back together, fast, for the clack
burstAmt.k = 160;
burstAmt.c = 15;
burstAmt.t = 0;
twist.t = 0;
closing = true;
}),
);
};
let visible = true;
const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting), { rootMargin: "80px" });
io.observe(root);
const tick = (_time: number, dms: number) => {
const dt = Math.min(0.05, Math.max(0.001, dms / 1000));
t += dt;
const L2 = live.current;
// tumble: a drag steers it; let go and it coasts back to the slow tumble
if (drag) w.lerp(dragW, 1 - Math.exp(-dt * 20));
else w.lerp(tmp.copy(idleW).multiplyScalar(still ? 0 : L2.speed), 1 - Math.exp(-dt * 0.6));
dragW.multiplyScalar(Math.exp(-dt * 6));
const s0 = w.length();
if (s0 > 1e-5) {
dq.setFromAxisAngle(tmp.copy(w).divideScalar(s0), s0 * dt);
spin.quaternion.premultiply(dq).normalize();
}
const px = pointer ? (pointer.x / W) * 2 - 1 : 0;
const py = pointer ? -((pointer.y / H) * 2 - 1) : 0;
leanX.t = still ? 0 : -py * 0.35;
leanY.t = still ? 0 : px * 0.45;
[leanX, leanY, squash, burstAmt, twist].forEach((s) => step(s, dt));
lean.rotation.set(leanX.x, leanY.x, 0);
lean.position.set(px * 0.08, (still ? 0 : Math.sin(t * 0.9) * 0.04) + py * 0.06, 0);
const q = Math.max(0.7, squash.x);
squashG.scale.set(1 / Math.sqrt(q), q, 1 / Math.sqrt(q));
// the pieces fly out along their corners and tumble, then fly home
const b = Math.max(-0.1, burstAmt.x);
pieces.forEach((p) => {
p.mesh.position.copy(p.dir).multiplyScalar(S / 4 + b * 0.42);
qp.setFromAxisAngle(p.axis, twist.x * 1.6);
p.mesh.quaternion.copy(qp);
});
if (closing && burstAmt.x < 0.015 && Math.abs(twist.x) < 0.02) {
// clack: they meet, the cube is whole again, and the shock squashes it
closing = false;
burstAmt.x = burstAmt.v = 0;
twist.x = twist.v = 0;
burstAmt.k = 90;
burstAmt.c = 9;
piecesG.visible = false;
whole.visible = true;
squash.v -= 2.6;
flashGoal = 0.7;
calls.push(gsap.delayedCall(0.35, () => (busy = false)));
}
flash += (flashGoal - flash) * (1 - Math.exp(-dt * 20));
flashGoal *= Math.exp(-dt * 3.5);
for (const m of [wholeMat, pieceMat]) {
m.uniforms.uFlash.value = flash;
m.uniforms.uFire.value = L2.dispersion;
}
if (visible && W) renderer.render(scene, camera);
};
gsap.ticker.add(tick);
const local = (e: PointerEvent) => {
const r = root.getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top };
};
const onMove = (e: PointerEvent) => {
pointer = local(e);
if (!drag) return;
const now = performance.now();
const ddt = Math.max(8, now - drag.t) / 1000;
const dx = (e.clientX - drag.x) / root.clientWidth, dy = (e.clientY - drag.y) / root.clientHeight;
dragW.set((dy / ddt) * 4, (dx / ddt) * 4, 0).clampLength(0, 12);
drag.x = e.clientX;
drag.y = e.clientY;
drag.t = now;
};
const onDown = (e: PointerEvent) => {
if (e.button !== 0) return;
const now = performance.now();
drag = { x: e.clientX, y: e.clientY, t: now, sx: e.clientX, sy: e.clientY, t0: now, id: e.pointerId };
dragW.copy(w);
try {
root.setPointerCapture(e.pointerId);
} catch {
/* synthetic pointers can't be captured */
}
};
const onUp = (e: PointerEvent) => {
if (!drag) return;
const moved = Math.hypot(e.clientX - drag.sx, e.clientY - drag.sy);
const quick = performance.now() - drag.t0 < 450;
try {
root.releasePointerCapture(drag.id);
} catch {
/* not captured */
}
drag = null;
if (moved < 7 && quick) burst();
};
const onLeave = () => {
if (!drag) pointer = null;
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
burst();
} else if (e.key.startsWith("Arrow")) {
e.preventDefault();
if (e.key === "ArrowLeft") w.y -= 2;
if (e.key === "ArrowRight") w.y += 2;
if (e.key === "ArrowUp") w.x -= 2;
if (e.key === "ArrowDown") w.x += 2;
}
};
root.addEventListener("pointermove", onMove);
root.addEventListener("pointerdown", onDown);
root.addEventListener("pointerup", onUp);
root.addEventListener("pointercancel", onUp);
root.addEventListener("pointerleave", onLeave);
root.addEventListener("keydown", onKey);
return () => {
gsap.ticker.remove(tick);
calls.forEach((c) => c.kill());
io.disconnect();
ro.disconnect();
root.removeEventListener("pointermove", onMove);
root.removeEventListener("pointerdown", onDown);
root.removeEventListener("pointerup", onUp);
root.removeEventListener("pointercancel", onUp);
root.removeEventListener("pointerleave", onLeave);
root.removeEventListener("keydown", onKey);
[wholeGeo, pieceGeo].forEach((g) => g.dispose());
[wholeMat, pieceMat].forEach((m) => m.dispose());
env.dispose();
pmrem.dispose();
renderer.dispose();
canvas.remove();
};
}, [palette, background]);
return (
<div
ref={rootRef}
tabIndex={0}
role="button"
aria-label="Glass cube. Drag to tumble it, press to crack it open."
className={["relative h-full min-h-[280px] w-full cursor-grab touch-none overflow-hidden outline-none select-none active:cursor-grabbing", className].filter(Boolean).join(" ")}
style={{ background }}
/>
);
}
export default PrismCube;
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
6 propspalette"neon" | "aurora" | "sunset"Colours of the light panels the glass refracts.default "neon"default "neon"dispersionnumberHow far red, green and blue split, 0 to 2.default 1default 1speednumberSpeed of the idle tumble (0 = still).default 1default 1backgroundstringBackground colour.default "#000000"default "#000000"onBurst() => voidCalled when the cube cracks open.classNamestringExtra classes (it fills its parent).