Glossy toys physics 3D hero
Glossy toy shapes float around the headline. Shove them with the cursor and they bump and spring back; drop them into a pile, shake them up, or click one to squeeze and repaint it.
"use client";
import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { RoundedBoxGeometry } from "three/addons/geometries/RoundedBoxGeometry.js";
import "./shapes-hero.css";
type ShapesHeroProps = {
studio?: string;
title?: string;
text?: string;
cta?: { label: string; href: string };
/** Colours the toys are painted in; clicking a toy moves it to the next one. */
palette?: string[];
};
type Body = {
mesh: THREE.Mesh;
r: number;
home: THREE.Vector2;
z: number;
vel: THREE.Vector3;
spin: THREE.Vector3;
squash: number;
colour: number;
};
const PALETTE = [
"#ff5a1f",
"#2b35ff",
"#d7ff3a",
"#ff9ec4",
"#f6f1e7",
"#1d1a16",
];
/**
* ShapesHero
* - Glossy toy shapes (spheres, pills, rings, soft cubes) float around the headline with real
* clearcoat reflections and soft shadows.
* - The cursor shoves them, they bump into each other and spring back home.
* - Drop lets gravity pile them on the floor; Shake throws them about; click one to squeeze it
* and repaint it.
*/
export function ShapesHero({
studio = "Plaything",
title = "We make things people want to touch.",
text = "A product studio for toys, tools and the small objects that end up on every desk. Push the shapes around; click one to squeeze it.",
cta = { label: "Start a project", href: "#plaything-start" },
palette = PALETTE,
}: ShapesHeroProps) {
const rootRef = useRef<HTMLElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
const actionsRef = useRef<{
drop: (on: boolean) => void;
shake: () => void;
} | null>(null);
const [dropped, setDropped] = useState(false);
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, alpha: true });
} catch {
const id = requestAnimationFrame(() => setFailed(true));
return () => cancelAnimationFrame(id);
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x000000, 0);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.toneMapping = THREE.NeutralToneMapping;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 80);
camera.position.set(0, 0, 14);
const pmrem = new THREE.PMREMGenerator(renderer);
const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
scene.environment = env;
scene.environmentIntensity = 0.9;
const sun = new THREE.DirectionalLight("#ffffff", 1.6);
sun.position.set(-3, 9, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.radius = 8;
sun.shadow.camera.left = -24;
sun.shadow.camera.right = 24;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
scene.add(sun);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 30),
new THREE.ShadowMaterial({ color: "#3a2a1a", opacity: 0.14 }),
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
/* ---- The toys ---- */
const small = stage.clientWidth < 700;
const COUNT = small ? 13 : 22;
const geos: Record<string, (r: number) => THREE.BufferGeometry> = {
ball: (r) => new THREE.SphereGeometry(r, 48, 32),
pill: (r) => new THREE.CapsuleGeometry(r * 0.55, r * 0.9, 10, 24),
ring: (r) => new THREE.TorusGeometry(r * 0.68, r * 0.3, 28, 64),
cube: (r) =>
new RoundedBoxGeometry(r * 1.25, r * 1.25, r * 1.25, 6, r * 0.32),
};
const kinds = Object.keys(geos);
const bodies: Body[] = [];
const rand = (a: number, b: number) => a + Math.random() * (b - a);
for (let i = 0; i < COUNT; i++) {
const r = rand(0.38, 0.78);
const colour = i % palette.length;
const mat = new THREE.MeshPhysicalMaterial({
color: palette[colour],
roughness: 0.32,
clearcoat: 1,
clearcoatRoughness: 0.18,
sheen: 0.4,
});
const mesh = new THREE.Mesh(geos[kinds[i % kinds.length]](r), mat);
mesh.castShadow = true;
mesh.rotation.set(rand(0, 6), rand(0, 6), rand(0, 6));
mesh.userData.i = i;
scene.add(mesh);
bodies.push({
mesh,
r,
home: new THREE.Vector2(),
z: rand(-1.6, 0.6),
vel: new THREE.Vector3(),
spin: new THREE.Vector3(
rand(-0.4, 0.4),
rand(-0.4, 0.4),
rand(-0.4, 0.4),
),
squash: 0,
colour,
});
}
/* ---- Homes: spread around the edges, leaving the headline clear ---- */
let halfW = 6;
let halfH = 3.75;
// Two layouts: an oval clearing on wide screens, a clear middle band on phones.
const makeHomes = (narrow: boolean) => {
const out: THREE.Vector2[] = [];
for (let tries = 0; out.length < COUNT && tries < 4000; tries++) {
const u = rand(-0.94, 0.94);
const v = rand(-0.88, 0.8);
if ((u / 0.62) ** 2 + (v / 0.5) ** 2 < 1) continue;
if (narrow && Math.abs(v + 0.05) < 0.42) continue;
if (out.some((h) => Math.hypot(h.x - u, (h.y - v) * 0.8) < 0.26))
continue;
out.push(new THREE.Vector2(u, v));
}
while (out.length < COUNT)
out.push(new THREE.Vector2(rand(-0.9, 0.9), rand(0.55, 0.85)));
return out;
};
const homes = { wide: makeHomes(false), narrow: makeHomes(true) };
const resize = (w: number, h: number) => {
if (w < 2 || h < 2) return;
renderer.setSize(w, h, false);
camera.aspect = w / h;
// Narrow screens: step back so the toys stay toy-sized.
camera.position.z = Math.min(26, 14 * Math.max(1, 1.1 / camera.aspect));
camera.updateProjectionMatrix();
halfH =
Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * camera.position.z;
halfW = halfH * camera.aspect;
floor.position.y = -halfH;
const set = camera.aspect < 0.8 ? homes.narrow : homes.wide;
bodies.forEach((b, i) => b.home.set(set[i].x * halfW, set[i].y * halfH));
};
const ro = new ResizeObserver(([e]) =>
resize(e.contentRect.width, e.contentRect.height),
);
ro.observe(stage);
resize(stage.clientWidth, stage.clientHeight);
bodies.forEach((b) =>
b.mesh.position.set(
b.home.x,
b.home.y + (reduce ? 0 : 8 + Math.random() * 6),
b.z,
),
);
/* ---- Pointer ---- */
const ray = new THREE.Raycaster();
const ndc = new THREE.Vector2();
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const pointer = new THREE.Vector3();
const pointerVel = new THREE.Vector3();
let pointerOn = false;
const toWorld = (e: PointerEvent) => {
const r = stage.getBoundingClientRect();
ndc.set(
((e.clientX - r.left) / r.width) * 2 - 1,
-((e.clientY - r.top) / r.height) * 2 + 1,
);
ray.setFromCamera(ndc, camera);
};
const prev = new THREE.Vector3();
const onMove = (e: PointerEvent) => {
toWorld(e);
prev.copy(pointer);
if (!ray.ray.intersectPlane(plane, pointer)) return;
if (pointerOn) pointerVel.subVectors(pointer, prev).clampLength(0, 1.2);
pointerOn = true;
};
const onLeave = () => {
pointerOn = false;
};
const onDown = (e: PointerEvent) => {
toWorld(e);
const hit = ray.intersectObjects(
bodies.map((b) => b.mesh),
false,
)[0];
if (!hit) return;
const b = bodies[hit.object.userData.i as number];
b.squash = 1;
b.colour = (b.colour + 1) % palette.length;
(b.mesh.material as THREE.MeshPhysicalMaterial).color.set(
palette[b.colour],
);
if (!reduce) {
b.vel.y += 5;
b.spin.add(new THREE.Vector3(rand(-4, 4), rand(-4, 4), rand(-4, 4)));
}
};
stage.addEventListener("pointermove", onMove);
stage.addEventListener("pointerleave", onLeave);
stage.addEventListener("pointerdown", onDown);
let gravity = false;
let active = !reduce;
actionsRef.current = {
drop(on) {
gravity = on;
active = true;
bodies.forEach((b) =>
b.vel.add(new THREE.Vector3(rand(-1, 1), on ? 0 : 6, 0)),
);
},
shake() {
active = true;
bodies.forEach((b) => {
b.vel.add(new THREE.Vector3(rand(-9, 9), rand(4, 12), rand(-2, 2)));
b.spin.add(new THREE.Vector3(rand(-6, 6), rand(-6, 6), rand(-6, 6)));
});
},
};
/* ---- Physics: springs home (or gravity), shoves, bumps ---- */
const tmp = new THREE.Vector3();
const n = new THREE.Vector3();
const q = new THREE.Quaternion();
const step = (dt: number, t: number) => {
for (const b of bodies) {
const p = b.mesh.position;
if (gravity) {
b.vel.y -= 22 * dt;
} else {
const bob = reduce ? 0 : Math.sin(t * 0.9 + b.r * 9) * 0.12;
tmp.set(b.home.x - p.x, b.home.y + bob - p.y, b.z - p.z);
b.vel.addScaledVector(tmp, 7 * dt);
b.vel.multiplyScalar(Math.exp(-2.6 * dt));
}
// The cursor shoves anything near it, harder when it moves fast.
if (pointerOn && !reduce) {
tmp.subVectors(p, pointer);
tmp.z *= 0.4;
const d = tmp.length();
const reach = b.r + 1.1;
if (d < reach) {
const f = (1 - d / reach) * 26;
b.vel.addScaledVector(tmp.normalize(), f * dt);
b.vel.addScaledVector(pointerVel, 18 * dt);
b.spin.x += pointerVel.y * 2;
b.spin.y -= pointerVel.x * 2;
}
}
p.addScaledVector(b.vel, dt);
// Walls and floor when dropped.
if (gravity) {
const floorY = -halfH + b.r;
if (p.y < floorY) {
p.y = floorY;
b.vel.y *= -0.42;
b.vel.x *= 0.9;
b.spin.multiplyScalar(0.9);
}
b.vel.multiplyScalar(Math.exp(-0.25 * dt));
}
const wall = halfW - b.r;
if (Math.abs(p.x) > wall) {
p.x = Math.sign(p.x) * wall;
b.vel.x *= -0.5;
}
if (p.z < -2.2 || p.z > 1.4) {
p.z = THREE.MathUtils.clamp(p.z, -2.2, 1.4);
b.vel.z *= -0.5;
}
}
// Bumps: push overlapping toys apart and trade a little speed.
for (let i = 0; i < bodies.length; i++) {
for (let j = i + 1; j < bodies.length; j++) {
const a = bodies[i];
const c = bodies[j];
n.subVectors(c.mesh.position, a.mesh.position);
const d = n.length();
const min = (a.r + c.r) * 0.92;
if (d > 0 && d < min) {
n.divideScalar(d);
const push = (min - d) / 2;
a.mesh.position.addScaledVector(n, -push);
c.mesh.position.addScaledVector(n, push);
const rel = tmp.subVectors(c.vel, a.vel).dot(n);
if (rel < 0) {
const imp = -rel * 0.65;
a.vel.addScaledVector(n, -imp);
c.vel.addScaledVector(n, imp);
a.spin.y += imp * 0.6;
c.spin.x -= imp * 0.6;
}
}
}
}
for (const b of bodies) {
b.spin.multiplyScalar(Math.exp(-1.2 * dt));
const s = b.spin.length();
if (s > 1e-4) {
q.setFromAxisAngle(tmp.copy(b.spin).divideScalar(s), s * dt);
b.mesh.quaternion.premultiply(q);
}
// A squeeze: squash, overshoot, settle.
b.squash *= Math.exp(-5 * dt);
const k = Math.sin(b.squash * 9) * b.squash * 0.35;
b.mesh.scale.set(1 + k, 1 - k, 1 + k);
}
};
/* ---- Loop ---- */
let raf = 0;
let visible = true;
const t0 = performance.now();
let last = t0;
const loop = (now: number) => {
raf = 0;
if (!visible || document.hidden) return;
const dt = Math.min(1 / 30, (now - last) / 1000);
last = now;
if (active) {
step(dt / 2, (now - t0) / 1000);
step(dt / 2, (now - t0) / 1000);
} else {
// Reduced motion and nothing pressed: only squeezes play out.
for (const b of bodies) {
b.squash = 0;
b.mesh.scale.setScalar(1);
}
}
pointerVel.multiplyScalar(0.8);
renderer.render(scene, camera);
raf = requestAnimationFrame(loop);
};
const wake = () => {
if (!raf && visible && !document.hidden) {
last = performance.now();
raf = requestAnimationFrame(loop);
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
wake();
});
io.observe(stage);
document.addEventListener("visibilitychange", wake);
wake();
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
document.removeEventListener("visibilitychange", wake);
stage.removeEventListener("pointermove", onMove);
stage.removeEventListener("pointerleave", onLeave);
stage.removeEventListener("pointerdown", onDown);
actionsRef.current = null;
scene.traverse((o) => {
if (o instanceof THREE.Mesh) {
o.geometry.dispose();
(o.material as THREE.Material).dispose();
}
});
env.dispose();
pmrem.dispose();
renderer.dispose();
renderer.forceContextLoss();
renderer.domElement.remove();
};
}, [palette]);
const toggleDrop = () => {
actionsRef.current?.drop(!dropped);
setDropped(!dropped);
};
return (
<section
ref={rootRef}
className="gu-play"
data-failed={failed || undefined}
aria-labelledby="gu-play-title"
>
<div ref={stageRef} className="gu-play__stage" aria-hidden="true" />
{failed && (
<div className="gu-play__fallback" aria-hidden="true">
{palette.slice(0, 5).map((c, i) => (
<i
key={c}
style={{ background: c, animationDelay: `${i * 0.3}s` }}
/>
))}
</div>
)}
<header className="gu-play__bar">
<a className="gu-play__mark" href="#">
<span aria-hidden="true" />
{studio}
</a>
<nav aria-label="Main">
<a href="#plaything-work">Work</a>
<a href="#plaything-studio">Studio</a>
<a className="gu-play__navcta" href={cta.href}>
{cta.label}
</a>
</nav>
</header>
<div className="gu-play__copy">
<h1 id="gu-play-title">{title}</h1>
<p>{text}</p>
</div>
<div
className="gu-play__toys"
role="group"
aria-label="Play with the shapes"
>
<button type="button" onClick={toggleDrop} aria-pressed={dropped}>
<svg viewBox="0 0 24 24" aria-hidden="true">
{dropped ? (
<path d="M12 19V5M6 11l6-6 6 6" />
) : (
<path d="M12 5v14M6 13l6 6 6-6" />
)}
</svg>
{dropped ? "Float them" : "Drop them"}
</button>
<button type="button" onClick={() => actionsRef.current?.shake()}>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 8l3-3M4 16l3 3M20 8l-3-3M20 16l-3 3M9 12h6" />
</svg>
Shake
</button>
</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: Glossy toys physics 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 hero for a product design studio ("Plaything"). Glossy toy shapes (three.js) float around a big centred headline. They react to the cursor with a small hand-written physics loop: shoves, bumps, springs, gravity.
## Layout and look
- Section min-height 760px, warm studio paper (#efe7da to #e6dccb) with a pale glow behind the headline. Ink #1d1a16, muted #6c6255.
- Top bar: a glossy orange dot logo that squashes on hover, a heavy wordmark, two links and a dark pill CTA that tips on hover.
- Centre: a very heavy, tight h1 (up to 5.6rem) and one muted line; both pop in with a springy ease.
- Bottom centre: two chunky "key" buttons (2px ink border and a 5px solid shadow that presses flat on click). One is "Drop them" / "Float them" (aria-pressed, orange when pressed), the other is "Shake".
## The 3D scene
1. 22 toys (13 on narrow screens): spheres, capsules, tori and rounded boxes, radius 0.38–0.78. MeshPhysicalMaterial with roughness 0.32, clearcoat 1 and a little sheen, in orange, ultramarine, volt, pink, cream and ink. RoomEnvironment reflections and NeutralToneMapping.
2. A directional light with PCF shadows (radius 8) falls on a ShadowMaterial floor at the bottom edge of the view.
3. Homes: random points (in -1..1 view units) that keep out of a central ellipse so the headline stays clear, spaced apart, and scaled to the visible width and height at z = 0 on resize. The toys fall in from above on load.
## Physics (two sub-steps a frame)
- Floating: a spring to home (+ a gentle bob) with damping.
- Dropped: gravity, floor bounce (0.42), wall bounce, light drag.
- Cursor: raycast to the z = 0 plane. Toys within r + 1.1 are pushed away and also pick up the pointer's velocity and some spin.
- Bumps: overlapping pairs are pushed apart, and their closing speed along the normal is exchanged with restitution plus spin.
- Spin is integrated as an axis-angle quaternion with damping.
- A click on a toy squashes it (a decaying sine on the scale), paints it the next palette colour, and pops it up.
- Shake: random impulses and spin for everyone.
## Accessibility
The canvas is decorative. The headline and copy are real text, and the two buttons have visible labels (aria-pressed on the toggle).
## Reduced motion
No bob or shove; the toys sit still until Drop or Shake is pressed, and a click only repaints. No entrance animation.
## Props
studio, title, text, cta ({ label, href }), palette (colour list).
## 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.
### ShapesHero.tsx
```tsx
"use client";
import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { RoundedBoxGeometry } from "three/addons/geometries/RoundedBoxGeometry.js";
import "./shapes-hero.css";
type ShapesHeroProps = {
studio?: string;
title?: string;
text?: string;
cta?: { label: string; href: string };
/** Colours the toys are painted in; clicking a toy moves it to the next one. */
palette?: string[];
};
type Body = {
mesh: THREE.Mesh;
r: number;
home: THREE.Vector2;
z: number;
vel: THREE.Vector3;
spin: THREE.Vector3;
squash: number;
colour: number;
};
const PALETTE = [
"#ff5a1f",
"#2b35ff",
"#d7ff3a",
"#ff9ec4",
"#f6f1e7",
"#1d1a16",
];
/**
* ShapesHero
* - Glossy toy shapes (spheres, pills, rings, soft cubes) float around the headline with real
* clearcoat reflections and soft shadows.
* - The cursor shoves them, they bump into each other and spring back home.
* - Drop lets gravity pile them on the floor; Shake throws them about; click one to squeeze it
* and repaint it.
*/
export function ShapesHero({
studio = "Plaything",
title = "We make things people want to touch.",
text = "A product studio for toys, tools and the small objects that end up on every desk. Push the shapes around; click one to squeeze it.",
cta = { label: "Start a project", href: "#plaything-start" },
palette = PALETTE,
}: ShapesHeroProps) {
const rootRef = useRef<HTMLElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
const actionsRef = useRef<{
drop: (on: boolean) => void;
shake: () => void;
} | null>(null);
const [dropped, setDropped] = useState(false);
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, alpha: true });
} catch {
const id = requestAnimationFrame(() => setFailed(true));
return () => cancelAnimationFrame(id);
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x000000, 0);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFShadowMap;
renderer.toneMapping = THREE.NeutralToneMapping;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 80);
camera.position.set(0, 0, 14);
const pmrem = new THREE.PMREMGenerator(renderer);
const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
scene.environment = env;
scene.environmentIntensity = 0.9;
const sun = new THREE.DirectionalLight("#ffffff", 1.6);
sun.position.set(-3, 9, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.radius = 8;
sun.shadow.camera.left = -24;
sun.shadow.camera.right = 24;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
scene.add(sun);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 30),
new THREE.ShadowMaterial({ color: "#3a2a1a", opacity: 0.14 }),
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
/* ---- The toys ---- */
const small = stage.clientWidth < 700;
const COUNT = small ? 13 : 22;
const geos: Record<string, (r: number) => THREE.BufferGeometry> = {
ball: (r) => new THREE.SphereGeometry(r, 48, 32),
pill: (r) => new THREE.CapsuleGeometry(r * 0.55, r * 0.9, 10, 24),
ring: (r) => new THREE.TorusGeometry(r * 0.68, r * 0.3, 28, 64),
cube: (r) =>
new RoundedBoxGeometry(r * 1.25, r * 1.25, r * 1.25, 6, r * 0.32),
};
const kinds = Object.keys(geos);
const bodies: Body[] = [];
const rand = (a: number, b: number) => a + Math.random() * (b - a);
for (let i = 0; i < COUNT; i++) {
const r = rand(0.38, 0.78);
const colour = i % palette.length;
const mat = new THREE.MeshPhysicalMaterial({
color: palette[colour],
roughness: 0.32,
clearcoat: 1,
clearcoatRoughness: 0.18,
sheen: 0.4,
});
const mesh = new THREE.Mesh(geos[kinds[i % kinds.length]](r), mat);
mesh.castShadow = true;
mesh.rotation.set(rand(0, 6), rand(0, 6), rand(0, 6));
mesh.userData.i = i;
scene.add(mesh);
bodies.push({
mesh,
r,
home: new THREE.Vector2(),
z: rand(-1.6, 0.6),
vel: new THREE.Vector3(),
spin: new THREE.Vector3(
rand(-0.4, 0.4),
rand(-0.4, 0.4),
rand(-0.4, 0.4),
),
squash: 0,
colour,
});
}
/* ---- Homes: spread around the edges, leaving the headline clear ---- */
let halfW = 6;
let halfH = 3.75;
// Two layouts: an oval clearing on wide screens, a clear middle band on phones.
const makeHomes = (narrow: boolean) => {
const out: THREE.Vector2[] = [];
for (let tries = 0; out.length < COUNT && tries < 4000; tries++) {
const u = rand(-0.94, 0.94);
const v = rand(-0.88, 0.8);
if ((u / 0.62) ** 2 + (v / 0.5) ** 2 < 1) continue;
if (narrow && Math.abs(v + 0.05) < 0.42) continue;
if (out.some((h) => Math.hypot(h.x - u, (h.y - v) * 0.8) < 0.26))
continue;
out.push(new THREE.Vector2(u, v));
}
while (out.length < COUNT)
out.push(new THREE.Vector2(rand(-0.9, 0.9), rand(0.55, 0.85)));
return out;
};
const homes = { wide: makeHomes(false), narrow: makeHomes(true) };
const resize = (w: number, h: number) => {
if (w < 2 || h < 2) return;
renderer.setSize(w, h, false);
camera.aspect = w / h;
// Narrow screens: step back so the toys stay toy-sized.
camera.position.z = Math.min(26, 14 * Math.max(1, 1.1 / camera.aspect));
camera.updateProjectionMatrix();
halfH =
Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * camera.position.z;
halfW = halfH * camera.aspect;
floor.position.y = -halfH;
const set = camera.aspect < 0.8 ? homes.narrow : homes.wide;
bodies.forEach((b, i) => b.home.set(set[i].x * halfW, set[i].y * halfH));
};
const ro = new ResizeObserver(([e]) =>
resize(e.contentRect.width, e.contentRect.height),
);
ro.observe(stage);
resize(stage.clientWidth, stage.clientHeight);
bodies.forEach((b) =>
b.mesh.position.set(
b.home.x,
b.home.y + (reduce ? 0 : 8 + Math.random() * 6),
b.z,
),
);
/* ---- Pointer ---- */
const ray = new THREE.Raycaster();
const ndc = new THREE.Vector2();
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const pointer = new THREE.Vector3();
const pointerVel = new THREE.Vector3();
let pointerOn = false;
const toWorld = (e: PointerEvent) => {
const r = stage.getBoundingClientRect();
ndc.set(
((e.clientX - r.left) / r.width) * 2 - 1,
-((e.clientY - r.top) / r.height) * 2 + 1,
);
ray.setFromCamera(ndc, camera);
};
const prev = new THREE.Vector3();
const onMove = (e: PointerEvent) => {
toWorld(e);
prev.copy(pointer);
if (!ray.ray.intersectPlane(plane, pointer)) return;
if (pointerOn) pointerVel.subVectors(pointer, prev).clampLength(0, 1.2);
pointerOn = true;
};
const onLeave = () => {
pointerOn = false;
};
const onDown = (e: PointerEvent) => {
toWorld(e);
const hit = ray.intersectObjects(
bodies.map((b) => b.mesh),
false,
)[0];
if (!hit) return;
const b = bodies[hit.object.userData.i as number];
b.squash = 1;
b.colour = (b.colour + 1) % palette.length;
(b.mesh.material as THREE.MeshPhysicalMaterial).color.set(
palette[b.colour],
);
if (!reduce) {
b.vel.y += 5;
b.spin.add(new THREE.Vector3(rand(-4, 4), rand(-4, 4), rand(-4, 4)));
}
};
stage.addEventListener("pointermove", onMove);
stage.addEventListener("pointerleave", onLeave);
stage.addEventListener("pointerdown", onDown);
let gravity = false;
let active = !reduce;
actionsRef.current = {
drop(on) {
gravity = on;
active = true;
bodies.forEach((b) =>
b.vel.add(new THREE.Vector3(rand(-1, 1), on ? 0 : 6, 0)),
);
},
shake() {
active = true;
bodies.forEach((b) => {
b.vel.add(new THREE.Vector3(rand(-9, 9), rand(4, 12), rand(-2, 2)));
b.spin.add(new THREE.Vector3(rand(-6, 6), rand(-6, 6), rand(-6, 6)));
});
},
};
/* ---- Physics: springs home (or gravity), shoves, bumps ---- */
const tmp = new THREE.Vector3();
const n = new THREE.Vector3();
const q = new THREE.Quaternion();
const step = (dt: number, t: number) => {
for (const b of bodies) {
const p = b.mesh.position;
if (gravity) {
b.vel.y -= 22 * dt;
} else {
const bob = reduce ? 0 : Math.sin(t * 0.9 + b.r * 9) * 0.12;
tmp.set(b.home.x - p.x, b.home.y + bob - p.y, b.z - p.z);
b.vel.addScaledVector(tmp, 7 * dt);
b.vel.multiplyScalar(Math.exp(-2.6 * dt));
}
// The cursor shoves anything near it, harder when it moves fast.
if (pointerOn && !reduce) {
tmp.subVectors(p, pointer);
tmp.z *= 0.4;
const d = tmp.length();
const reach = b.r + 1.1;
if (d < reach) {
const f = (1 - d / reach) * 26;
b.vel.addScaledVector(tmp.normalize(), f * dt);
b.vel.addScaledVector(pointerVel, 18 * dt);
b.spin.x += pointerVel.y * 2;
b.spin.y -= pointerVel.x * 2;
}
}
p.addScaledVector(b.vel, dt);
// Walls and floor when dropped.
if (gravity) {
const floorY = -halfH + b.r;
if (p.y < floorY) {
p.y = floorY;
b.vel.y *= -0.42;
b.vel.x *= 0.9;
b.spin.multiplyScalar(0.9);
}
b.vel.multiplyScalar(Math.exp(-0.25 * dt));
}
const wall = halfW - b.r;
if (Math.abs(p.x) > wall) {
p.x = Math.sign(p.x) * wall;
b.vel.x *= -0.5;
}
if (p.z < -2.2 || p.z > 1.4) {
p.z = THREE.MathUtils.clamp(p.z, -2.2, 1.4);
b.vel.z *= -0.5;
}
}
// Bumps: push overlapping toys apart and trade a little speed.
for (let i = 0; i < bodies.length; i++) {
for (let j = i + 1; j < bodies.length; j++) {
const a = bodies[i];
const c = bodies[j];
n.subVectors(c.mesh.position, a.mesh.position);
const d = n.length();
const min = (a.r + c.r) * 0.92;
if (d > 0 && d < min) {
n.divideScalar(d);
const push = (min - d) / 2;
a.mesh.position.addScaledVector(n, -push);
c.mesh.position.addScaledVector(n, push);
const rel = tmp.subVectors(c.vel, a.vel).dot(n);
if (rel < 0) {
const imp = -rel * 0.65;
a.vel.addScaledVector(n, -imp);
c.vel.addScaledVector(n, imp);
a.spin.y += imp * 0.6;
c.spin.x -= imp * 0.6;
}
}
}
}
for (const b of bodies) {
b.spin.multiplyScalar(Math.exp(-1.2 * dt));
const s = b.spin.length();
if (s > 1e-4) {
q.setFromAxisAngle(tmp.copy(b.spin).divideScalar(s), s * dt);
b.mesh.quaternion.premultiply(q);
}
// A squeeze: squash, overshoot, settle.
b.squash *= Math.exp(-5 * dt);
const k = Math.sin(b.squash * 9) * b.squash * 0.35;
b.mesh.scale.set(1 + k, 1 - k, 1 + k);
}
};
/* ---- Loop ---- */
let raf = 0;
let visible = true;
const t0 = performance.now();
let last = t0;
const loop = (now: number) => {
raf = 0;
if (!visible || document.hidden) return;
const dt = Math.min(1 / 30, (now - last) / 1000);
last = now;
if (active) {
step(dt / 2, (now - t0) / 1000);
step(dt / 2, (now - t0) / 1000);
} else {
// Reduced motion and nothing pressed: only squeezes play out.
for (const b of bodies) {
b.squash = 0;
b.mesh.scale.setScalar(1);
}
}
pointerVel.multiplyScalar(0.8);
renderer.render(scene, camera);
raf = requestAnimationFrame(loop);
};
const wake = () => {
if (!raf && visible && !document.hidden) {
last = performance.now();
raf = requestAnimationFrame(loop);
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
wake();
});
io.observe(stage);
document.addEventListener("visibilitychange", wake);
wake();
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
document.removeEventListener("visibilitychange", wake);
stage.removeEventListener("pointermove", onMove);
stage.removeEventListener("pointerleave", onLeave);
stage.removeEventListener("pointerdown", onDown);
actionsRef.current = null;
scene.traverse((o) => {
if (o instanceof THREE.Mesh) {
o.geometry.dispose();
(o.material as THREE.Material).dispose();
}
});
env.dispose();
pmrem.dispose();
renderer.dispose();
renderer.forceContextLoss();
renderer.domElement.remove();
};
}, [palette]);
const toggleDrop = () => {
actionsRef.current?.drop(!dropped);
setDropped(!dropped);
};
return (
<section
ref={rootRef}
className="gu-play"
data-failed={failed || undefined}
aria-labelledby="gu-play-title"
>
<div ref={stageRef} className="gu-play__stage" aria-hidden="true" />
{failed && (
<div className="gu-play__fallback" aria-hidden="true">
{palette.slice(0, 5).map((c, i) => (
<i
key={c}
style={{ background: c, animationDelay: `${i * 0.3}s` }}
/>
))}
</div>
)}
<header className="gu-play__bar">
<a className="gu-play__mark" href="#">
<span aria-hidden="true" />
{studio}
</a>
<nav aria-label="Main">
<a href="#plaything-work">Work</a>
<a href="#plaything-studio">Studio</a>
<a className="gu-play__navcta" href={cta.href}>
{cta.label}
</a>
</nav>
</header>
<div className="gu-play__copy">
<h1 id="gu-play-title">{title}</h1>
<p>{text}</p>
</div>
<div
className="gu-play__toys"
role="group"
aria-label="Play with the shapes"
>
<button type="button" onClick={toggleDrop} aria-pressed={dropped}>
<svg viewBox="0 0 24 24" aria-hidden="true">
{dropped ? (
<path d="M12 19V5M6 11l6-6 6 6" />
) : (
<path d="M12 5v14M6 13l6 6 6-6" />
)}
</svg>
{dropped ? "Float them" : "Drop them"}
</button>
<button type="button" onClick={() => actionsRef.current?.shake()}>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 8l3-3M4 16l3 3M20 8l-3-3M20 16l-3 3M9 12h6" />
</svg>
Shake
</button>
</div>
</section>
);
}
```
### shapes-hero.css
```css
/* Plaything: a warm studio table covered in glossy toys; the headline sits in the clearing. */
.gu-play {
--bg: #efe7da;
--ink: #1d1a16;
--muted: #6c6255;
--line: rgb(29 26 22 / 0.15);
--orange: #ff5a1f;
--focus: #2b35ff;
--ease: cubic-bezier(0.22, 1, 0.36, 1);
--spring: cubic-bezier(0.34, 1.56, 0.64, 1);
position: relative;
container-type: inline-size;
display: grid;
grid-template-rows: auto 1fr auto;
min-height: 760px;
overflow: hidden;
isolation: isolate;
background:
radial-gradient(60% 50% at 50% 45%, #fbf6ee, transparent 70%),
linear-gradient(#efe7da, #e6dccb);
color: var(--ink);
font-family:
system-ui,
-apple-system,
"Segoe UI",
sans-serif;
line-height: 1.5;
}
.gu-play *,
.gu-play *::before,
.gu-play *::after {
box-sizing: border-box;
}
.gu-play a {
color: inherit;
}
.gu-play :focus-visible {
outline: 3px solid var(--focus);
outline-offset: 3px;
}
.gu-play__stage {
position: absolute;
inset: 0;
z-index: 0;
}
.gu-play__stage canvas {
display: block;
width: 100%;
height: 100%;
}
.gu-play__bar,
.gu-play__copy,
.gu-play__toys {
position: relative;
z-index: 1;
pointer-events: none;
}
.gu-play__bar a,
.gu-play__toys button {
pointer-events: auto;
}
.gu-play__bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24px 5%;
}
.gu-play__mark {
display: inline-flex;
align-items: center;
gap: 10px;
font-size: 1.3rem;
font-weight: 850;
letter-spacing: -0.03em;
text-decoration: none;
}
/* Logo: a squishy dot that squeezes on hover. */
.gu-play__mark span {
width: 20px;
height: 20px;
border-radius: 50%;
background: radial-gradient(
circle at 32% 30%,
#ffd0bd,
var(--orange) 55%,
#c63c0d
);
transition:
transform 0.5s var(--spring),
border-radius 0.5s var(--spring);
}
.gu-play__mark:hover span {
transform: scale(1.25, 0.8);
border-radius: 45%;
}
.gu-play__bar nav {
display: flex;
align-items: center;
gap: 24px;
font-size: 0.95rem;
}
.gu-play__bar nav > a:not(.gu-play__navcta) {
text-decoration: none;
opacity: 0.8;
}
.gu-play__navcta {
padding: 11px 20px;
border-radius: 999px;
background: var(--ink);
color: var(--bg) !important;
font-weight: 700;
text-decoration: none;
transition: transform 0.4s var(--spring);
}
.gu-play__navcta:hover {
transform: scale(1.05) rotate(-2deg);
}
.gu-play__copy {
align-self: center;
justify-self: center;
max-width: min(760px, 70cqi);
text-align: center;
}
.gu-play__copy h1 {
margin: 0 0 18px;
font-size: clamp(2.6rem, 6.4cqi, 5.6rem);
font-weight: 900;
line-height: 0.92;
letter-spacing: -0.045em;
text-wrap: balance;
animation: gu-play-pop 1s var(--spring) 0.2s both;
}
.gu-play__copy p {
max-width: 46ch;
margin: 0 auto;
color: var(--muted);
font-size: 1.05rem;
animation: gu-play-pop 1s var(--spring) 0.35s both;
}
/* The toy controls: two chunky buttons that press down like keys. */
.gu-play__toys {
justify-self: center;
display: flex;
gap: 10px;
padding: 0 5% 34px;
animation: gu-play-pop 1s var(--spring) 0.5s both;
}
.gu-play__toys button {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 48px;
padding: 0 20px;
border: 2px solid var(--ink);
border-radius: 14px;
background: #fbf6ee;
color: var(--ink);
font: inherit;
font-weight: 700;
cursor: pointer;
box-shadow: 0 5px 0 var(--ink);
transition:
transform 0.15s var(--ease),
box-shadow 0.15s var(--ease),
background-color 0.3s;
}
.gu-play__toys button:hover {
background: #fff;
}
.gu-play__toys button:active {
transform: translateY(4px);
box-shadow: 0 1px 0 var(--ink);
}
.gu-play__toys button[aria-pressed="true"] {
background: var(--orange);
color: #fff;
}
.gu-play__toys svg {
width: 18px;
fill: none;
stroke: currentColor;
stroke-width: 2.2;
stroke-linecap: round;
stroke-linejoin: round;
}
@keyframes gu-play-pop {
from {
opacity: 0;
transform: translateY(28px) scale(0.96);
}
}
/* No WebGL: a few CSS balls bobbing at the edges. */
.gu-play__fallback i {
position: absolute;
width: 9cqi;
aspect-ratio: 1;
border-radius: 50%;
box-shadow: inset -10px -14px 24px rgb(0 0 0 / 0.18);
animation: gu-play-bob 3s ease-in-out infinite alternate;
}
.gu-play__fallback i:nth-child(1) {
left: 6%;
top: 20%;
}
.gu-play__fallback i:nth-child(2) {
right: 8%;
top: 16%;
}
.gu-play__fallback i:nth-child(3) {
left: 12%;
bottom: 14%;
}
.gu-play__fallback i:nth-child(4) {
right: 14%;
bottom: 18%;
}
.gu-play__fallback i:nth-child(5) {
left: 46%;
bottom: 6%;
width: 6cqi;
}
@keyframes gu-play-bob {
to {
translate: 0 -14px;
}
}
@container (max-width: 720px) {
.gu-play__bar nav > a:not(.gu-play__navcta) {
display: none;
}
.gu-play__copy {
max-width: 88cqi;
}
}
@media (prefers-reduced-motion: reduce) {
.gu-play *,
.gu-play *::before {
animation: none !important;
}
}
```
You might also want
Next piece: Illustrator portfolio with a print tableContour map 3D hero
Components, advanced, needs three
Glass prism 3D hero
Components, advanced, needs three
Liquid blob album 3D hero
Components, advanced, needs three