← All components Next componentMoebius Ribbon→
Typography · Particles
Kinetic Gravity
Your text built from thousands of blocks on a wall: the cursor blows them off, they float upward and snap back into the letters. Click for a shockwave.
<KineticGravityText3D />Live
Sweep through it · click to scatter
Customize
Blocks
Color#e4e4e7
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add kinetic-gravity
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber @react-three/drei && npm install -D @types/three
02
Add the component
One self-contained file: create components/KineticGravityText3D.tsx and paste it in.
components/KineticGravityText3D.tsx
1"use client";23import {4 Component,5 memo,6 Suspense,7 useEffect,8 useLayoutEffect,9 useMemo,10 useRef,11 useState,12 type CSSProperties,13 type ReactNode,14 type RefObject,15} from "react";16import * as THREE from "three";17import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";18import { Environment, Lightformer } from "@react-three/drei";1920/**21 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep22 * their own tailored scenes).23 *24 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its25 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):26 *27 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }28 *29 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,30 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are31 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.32 */3334/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */35export type TiltAxis = "both" | "x-only" | "y-only" | "none";3637/** 1. Cursor: how the pointer pulls, pushes and drags the object. */38interface CursorProps {39 /** Reach of the pointer's influence, in the component's own space: CSS pixels for pixel-laid-out widgets, world units for 3D scenes (each component says which). Default 220 (px). */40 cursorRadius?: number;41 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */42 cursorForce?: number;43 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */44 magneticStrength?: number;45 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */46 cursorDamping?: number;47}4849/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */50interface TiltProps {51 /** Largest lean towards the pointer, in degrees. Default 15. */52 maxTiltAngle?: number;53 /** Axes that follow the pointer. Default "both". */54 tiltAxis?: TiltAxis;55 /** Lean away from the pointer instead of towards it. Default false. */56 invertTilt?: boolean;57 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */58 parallaxOffset?: number;59}6061/** 3. Text and 3D typography, for components that draw a label. */62interface Text3DProps {63 /** The label drawn by the component. */64 text?: string;65 /** Scale of the lettering. Default 1. */66 fontSize?: number;67 /** Extrusion depth of 3D letters. Default 0.2. */68 textDepth?: number;69 /** Bevelled, light-catching edges on 3D letters. Default true. */70 bevelEnabled?: boolean;71 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */72 fontUrl?: string;73}7475/** 4. Rendering, materials and glow. */76interface MaterialProps {77 /** Main color of the object. Default "#6366f1". */78 primaryColor?: string;79 /** Color of the glow. Default "#00f0ff". */80 emissiveColor?: string;81 /** Strength of the glow, 0 (none) to 3. Default 1. */82 emissiveIntensity?: number;83 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */84 roughness?: number;85 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */86 metalness?: number;87 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */88 transmission?: number;89 /** Technical wireframe rendering. Default false. */90 wireframe?: boolean;91}9293/** 5. Particles, idle motion and shader animation. */94interface MotionProps {95 /** Number of instanced elements. Default depends on the component. */96 particleCount?: number;97 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */98 autoRotateSpeed?: number;99 /** Pulses or ripples per second. Default 1. */100 pulseRate?: number;101 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */102 displacementScale?: number;103}104105/** 6. Environment and camera. */106interface EnvironmentProps {107 /** Camera field of view, in degrees. Default depends on the component. */108 cameraFov?: number;109 /** Color of the depth fog. Default "#0a0a0a". */110 fogColor?: string;111 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */112 fogDensity?: number;113}114115/** 7. Performance and accessibility. */116interface PerformanceProps {117 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */118 lowPowerMode?: boolean;119 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */120 respectReducedMotion?: boolean;121 /** Stop the render loop while the component is scrolled out of view. Default true. */122 pauseWhenOffscreen?: boolean;123}124125/** Every group at once. Components extend only the groups they apply (see the top of this file). */126interface Base3DComponentProps127 extends CursorProps,128 TiltProps,129 Text3DProps,130 MaterialProps,131 MotionProps,132 EnvironmentProps,133 PerformanceProps {}134135type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;136137/** The values a prop takes when it is left out. A component may override one, and then documents it. */138const DEFAULT_3D_PROPS: Defaults = {139 cursorRadius: 220,140 cursorForce: 1,141 magneticStrength: 0,142 cursorDamping: 0.1,143 maxTiltAngle: 15,144 tiltAxis: "both",145 invertTilt: false,146 parallaxOffset: 1,147 fontSize: 1,148 textDepth: 0.2,149 bevelEnabled: true,150 primaryColor: "#6366f1",151 emissiveColor: "#00f0ff",152 emissiveIntensity: 1,153 roughness: 0.3,154 metalness: 0.5,155 transmission: 0,156 wireframe: false,157 autoRotateSpeed: 0,158 pulseRate: 1,159 displacementScale: 1,160 fogColor: "#0a0a0a",161 fogDensity: 0,162 lowPowerMode: false,163 respectReducedMotion: true,164 pauseWhenOffscreen: true,165};166167/** Fills the positioned parent and receives pointer events. */168const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };169170/** Visually hidden but read by screen readers (the canvas itself is aria-hidden). */171const SR_ONLY: CSSProperties = {172 position: "absolute",173 width: 1,174 height: 1,175 padding: 0,176 margin: -1,177 overflow: "hidden",178 clip: "rect(0, 0, 0, 0)",179 whiteSpace: "nowrap",180 border: 0,181};182183interface TypeCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {184 children: ReactNode;185 /** The text, for screen readers. */186 label: string;187 /** HTML laid over the canvas (controls…). */188 overlay?: ReactNode;189}190191/**192 * Ready-to-use <Canvas> shared by the typography components: fills its positioned parent, pauses193 * its render loop while scrolled out of view, exposes the text to screen readers, and R3F disposes194 * the renderer and its WebGL context on unmount. A font that fails to load leaves an empty canvas.195 */196function TypeCanvas({ children, label, overlay, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: TypeCanvasProps) {197 const containerRef = useRef<HTMLDivElement>(null);198 const [inView, setInView] = useState(true);199200 useEffect(() => {201 const el = containerRef.current;202 if (!el) return undefined;203 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));204 observer.observe(el);205 return () => observer.disconnect();206 }, []);207208 return (209 <div ref={containerRef} style={FILL_STYLE}>210 <span style={SR_ONLY}>{label}</span>211 <Canvas212 aria-hidden="true"213 dpr={lowPowerMode ? 1 : dpr}214 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}215 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}216 style={{ touchAction: "pan-y" }}217 {...canvasProps}218 >219 <SceneBoundary>220 <Suspense fallback={null}>{children}</Suspense>221 </SceneBoundary>222 </Canvas>223 {overlay}224 </div>225 );226}227228class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {229 state = { failed: false };230 static getDerivedStateFromError() {231 return { failed: true };232 }233 render() {234 return this.state.failed ? null : this.props.children;235 }236}237238function usePrefersReducedMotion() {239 const [reduced, setReduced] = useState(false);240 useEffect(() => {241 const query = window.matchMedia("(prefers-reduced-motion: reduce)");242 const sync = () => setReduced(query.matches);243 sync();244 query.addEventListener("change", sync);245 return () => query.removeEventListener("change", sync);246 }, []);247 return reduced;248}249250interface CanvasPointer {251 /** Pointer position in normalized device coordinates of the canvas (-1..1). */252 ndc: THREE.Vector2;253 /** True while the pointer is over the canvas. */254 inside: boolean;255 /** Pointer speed, in NDC units per second (smoothed). */256 speed: number;257}258259/**260 * Tracks the pointer relative to the canvas through window listeners, so HTML laid over the canvas261 * never blocks it. Returns a ref read inside useFrame: pointer moves never re-render React.262 */263function useCanvasPointer(): RefObject<CanvasPointer> {264 const gl = useThree((state) => state.gl);265 const pointer = useRef<CanvasPointer>({ ndc: new THREE.Vector2(), inside: false, speed: 0 });266267 useEffect(() => {268 const el = gl.domElement;269 let lastTime = performance.now();270 const move = (event: PointerEvent) => {271 const rect = el.getBoundingClientRect();272 const p = pointer.current;273 const x = ((event.clientX - rect.left) / rect.width) * 2 - 1;274 const y = -((event.clientY - rect.top) / rect.height) * 2 + 1;275 const now = performance.now();276 const dt = Math.max(1, now - lastTime) / 1000;277 lastTime = now;278 p.speed = p.speed * 0.7 + (Math.hypot(x - p.ndc.x, y - p.ndc.y) / dt) * 0.3;279 p.ndc.set(x, y);280 p.inside = Math.abs(x) <= 1 && Math.abs(y) <= 1;281 };282 const leave = () => {283 pointer.current.inside = false;284 };285 window.addEventListener("pointermove", move, { passive: true });286 document.documentElement.addEventListener("pointerleave", leave);287 window.addEventListener("blur", leave);288 return () => {289 window.removeEventListener("pointermove", move);290 document.documentElement.removeEventListener("pointerleave", leave);291 window.removeEventListener("blur", leave);292 };293 }, [gl]);294295 return pointer;296}297298const plane = new THREE.Plane();299300const raycaster = new THREE.Raycaster();301302/** Where the pointer ray meets the plane z = `z` (world space), written into `target`. */303function pointerOnPlane(ndc: THREE.Vector2, camera: THREE.Camera, target: THREE.Vector3, z = 0) {304 plane.set(new THREE.Vector3(0, 0, 1), -z);305 raycaster.setFromCamera(ndc, camera);306 return raycaster.ray.intersectPlane(plane, target) ?? target;307}308309interface FitToViewProps {310 children: ReactNode;311 /** Size of the content in world units, at scale 1. Measured from the children when omitted. */312 size?: [number, number];313 /** Largest share of the view width the content may take. Default 0.86. */314 maxWidth?: number;315 /** Largest share of the view height the content may take. Default 0.62. */316 maxHeight?: number;317 /** Changes when the content changes, to measure it again. */318 measureKey?: unknown;319}320321/**322 * Scales its content down (never up) so that a long text still fits the canvas, on every size and323 * aspect ratio; the camera and the content can move freely inside.324 */325function FitToView({ children, size, maxWidth = 0.86, maxHeight = 0.62, measureKey }: FitToViewProps) {326 const outer = useRef<THREE.Group>(null);327 const inner = useRef<THREE.Group>(null);328 const measured = useRef(new THREE.Vector2(1, 1));329 const viewport = useThree((state) => state.viewport);330331 useLayoutEffect(() => {332 if (size) {333 measured.current.set(size[0], size[1]);334 return;335 }336 if (!inner.current || !outer.current) return;337 // World-space box, divided by the current fit scale: the size of the content at scale 1338 outer.current.updateWorldMatrix(true, true);339 const box = new THREE.Box3().setFromObject(inner.current, true);340 const scale = outer.current.getWorldScale(new THREE.Vector3()).x || 1;341 if (!box.isEmpty()) measured.current.set((box.max.x - box.min.x) / scale, (box.max.y - box.min.y) / scale);342 }, [size, measureKey]);343344 useFrame(() => {345 if (!outer.current) return;346 const { x, y } = measured.current;347 const scale = Math.min(1, (viewport.width * maxWidth) / Math.max(x, 1e-3), (viewport.height * maxHeight) / Math.max(y, 1e-3));348 outer.current.scale.setScalar(scale);349 });350351 return (352 <group ref={outer}>353 <group ref={inner}>{children}</group>354 </group>355 );356}357358/** The font of the page body, for text drawn on a 2D canvas. */359function pageFontFamily() {360 if (typeof document === "undefined") return "sans-serif";361 return getComputedStyle(document.body).fontFamily || "sans-serif";362}363364interface TextSample {365 /** Filled cells, centered on the origin, in world units (y up). */366 points: Float32Array;367 count: number;368 /** Distance between two neighbouring cells, in world units. */369 cell: number;370 width: number;371 height: number;372}373374/**375 * Rasterizes the text with a 2D canvas (any font the page has, every character) and returns the376 * centers of the filled cells of a grid with `rows` cells per line height, scaled so a line is377 * `lineHeight` world units tall. Used to build text out of particles or voxels.378 */379function sampleText(text: string, { rows = 24, lineHeight = 1, fontFamily, fontWeight = 800 }: { rows?: number; lineHeight?: number; fontFamily?: string; fontWeight?: number } = {}): TextSample {380 const lines = (text || " ").split("\n");381 const px = 6; // canvas pixels per grid cell382 const fontPx = rows * px;383 const canvas = document.createElement("canvas");384 const ctx = canvas.getContext("2d", { willReadFrequently: true })!;385 const font = `${fontWeight} ${fontPx}px ${fontFamily ?? pageFontFamily()}`;386 ctx.font = font;387 const textWidth = Math.max(...lines.map((line) => ctx.measureText(line).width), 1);388 const lineStep = fontPx * 1.1;389 canvas.width = Math.ceil(textWidth + px * 2);390 canvas.height = Math.ceil(lineStep * lines.length + px * 2);391 ctx.font = font;392 ctx.fillStyle = "#fff";393 ctx.textBaseline = "middle";394 lines.forEach((line, i) => ctx.fillText(line, px, px + lineStep * (i + 0.5)));395396 const { data, width, height } = ctx.getImageData(0, 0, canvas.width, canvas.height);397 const cols = Math.floor(width / px);398 const rowsTotal = Math.floor(height / px);399 const cell = lineHeight / rows;400 const found: number[] = [];401 for (let r = 0; r < rowsTotal; r++) {402 for (let c = 0; c < cols; c++) {403 // Sample the center of the cell404 const x = Math.floor(c * px + px / 2);405 const y = Math.floor(r * px + px / 2);406 if (data[(y * width + x) * 4 + 3] > 128) found.push((c - cols / 2 + 0.5) * cell, (rowsTotal / 2 - r - 0.5) * cell);407 }408 }409 return { points: new Float32Array(found), count: found.length / 2, cell, width: cols * cell, height: rowsTotal * cell };410}411412export interface KineticGravityTextProps extends Pick<MaterialProps, "primaryColor">, Pick<CursorProps, "cursorRadius">, Pick<Text3DProps, "text" | "fontSize">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {413 text: string;414 /** Shape of the blocks the letters are made of. Default "cube". */415 particleShape?: "cube" | "sphere";416 /** Reach of the cursor, in letter heights. Default 0.7. */417 cursorRadius?: number;418 /** @deprecated Use `cursorRadius`. */419 dispersalRadius?: number;420 /** Height of a line of text in world units (long texts are scaled down to fit). Default 1.4. */421 fontSize?: number;422 primaryColor?: string;423 /** @deprecated Use `primaryColor`. */424 color?: string;425 /** Blocks per line height: more blocks, finer letters. Default 26. */426 density?: number;427 /** CSS font the letters are drawn with. Default: the page's font. */428 fontFamily?: string;429}430431// Above this, the density is lowered so a long text stays at 60 fps432const MAX_BLOCKS = 6000;433434const Blocks = memo(function Blocks({ text, particleShape, dispersalRadius, fontSize, color, density, fontFamily }: Required<Omit<KineticGravityTextProps, "primaryColor" | "cursorRadius" | "pauseWhenOffscreen" | "lowPowerMode" | "fontFamily">> & { fontFamily?: string }) {435 const reducedMotion = usePrefersReducedMotion();436 const pointer = useCanvasPointer();437 const gl = useThree((state) => state.gl);438 const camera = useThree((state) => state.camera);439 const mesh = useRef<THREE.InstancedMesh>(null);440 const hit = useRef(new THREE.Vector3());441 const blast = useRef<THREE.Vector3 | null>(null);442443 const sample = useMemo(() => {444 let rows = density;445 let result = sampleText(text, { rows, lineHeight: fontSize, fontFamily });446 while (result.count > MAX_BLOCKS && rows > 8) {447 rows = Math.floor(rows * 0.85);448 result = sampleText(text, { rows, lineHeight: fontSize, fontFamily });449 }450 return result;451 }, [text, density, fontSize, fontFamily]);452453 // Per block: position, velocity, a random tumble axis and a random push depth454 const sim = useMemo(() => {455 const n = sample.count;456 const pos = new Float32Array(n * 3);457 const vel = new Float32Array(n * 3);458 const axis = new Float32Array(n * 3);459 const seed = new Float32Array(n);460 for (let i = 0; i < n; i++) {461 pos[i * 3] = sample.points[i * 2];462 pos[i * 3 + 1] = sample.points[i * 2 + 1];463 const a = new THREE.Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).normalize();464 axis.set([a.x, a.y, a.z], i * 3);465 seed[i] = Math.random();466 }467 return { pos, vel, axis, seed };468 }, [sample]);469470 const geometry = useMemo(471 () =>472 particleShape === "sphere"473 ? new THREE.SphereGeometry(sample.cell * 0.5, 10, 8)474 : new THREE.BoxGeometry(sample.cell * 0.86, sample.cell * 0.86, sample.cell * 0.86),475 [particleShape, sample.cell]476 );477 const material = useMemo(() => new THREE.MeshStandardMaterial({ metalness: 0.55, roughness: 0.28, envMapIntensity: 1.2 }), []);478 useEffect(() => () => geometry.dispose(), [geometry]);479 useEffect(() => () => material.dispose(), [material]);480481 const base = useMemo(() => new THREE.Color(color), [color]);482 const hot = useMemo(() => new THREE.Color(color).lerp(new THREE.Color("#ffffff"), 0.7), [color]);483484 // Click: a shockwave scatters the whole word, which then falls back into place485 useEffect(() => {486 const el = gl.domElement;487 const down = (event: PointerEvent) => {488 if (event.button !== 0 || !mesh.current) return;489 const rect = el.getBoundingClientRect();490 const ndc = new THREE.Vector2(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);491 const point = pointerOnPlane(ndc, camera, new THREE.Vector3());492 blast.current = mesh.current.worldToLocal(point);493 };494 el.addEventListener("pointerdown", down);495 return () => el.removeEventListener("pointerdown", down);496 }, [gl, camera]);497498 const dummy = useMemo(() => new THREE.Object3D(), []);499 const tint = useMemo(() => new THREE.Color(), []);500 const time = useRef(0);501502 useFrame((frame, delta) => {503 const m = mesh.current;504 if (!m) return;505 const dt = Math.min(delta, 1 / 30);506 time.current += dt;507 const t = time.current;508 const { pos, vel, axis, seed } = sim;509 const n = sample.count;510 const radius = dispersalRadius * fontSize;511512 // Pointer in the word's own space513 const p = pointer.current;514 let px = 1e6;515 let py = 1e6;516 if (p.inside) {517 pointerOnPlane(p.ndc, frame.camera, hit.current);518 m.worldToLocal(hit.current);519 px = hit.current.x;520 py = hit.current.y;521 }522 const sweep = Math.min(p.speed, 8) / 8; // a fast sweep scatters more523 const shock = blast.current;524 blast.current = null;525526 const stiffness = 16;527 const damping = Math.exp(-5 * dt);528 for (let i = 0; i < n; i++) {529 const ix = i * 3;530 const hx = sample.points[i * 2];531 const hy = sample.points[i * 2 + 1];532 let x = pos[ix];533 let y = pos[ix + 1];534 let z = pos[ix + 2];535536 // The cursor blows the blocks off the wall, toward the viewer537 const dx = x - px;538 const dy = y - py;539 const d2 = dx * dx + dy * dy;540 if (d2 < radius * radius) {541 const d = Math.sqrt(d2) + 1e-4;542 const f = (1 - d / radius) ** 1.5 * (55 + sweep * 90) * dt;543 vel[ix] += (dx / d) * f * radius;544 vel[ix + 1] += (dy / d) * f * radius;545 vel[ix + 2] += (0.6 + seed[i]) * f * radius * 2.2;546 }547 if (shock) {548 const sx = x - shock.x;549 const sy = y - shock.y;550 const sd = Math.sqrt(sx * sx + sy * sy) + 0.05;551 const f = (2.2 / (0.4 + sd)) * fontSize * (0.5 + seed[i]);552 vel[ix] += (sx / sd) * f;553 vel[ix + 1] += (sy / sd) * f;554 vel[ix + 2] += (seed[i] - 0.2) * f * 1.6;555 }556557 // Loose blocks float upward (inverse gravity), while a spring pulls each one home558 const ox = hx - x;559 const oy = hy - y;560 const loose = Math.min(1, Math.sqrt(ox * ox + oy * oy + z * z) / Math.max(radius, 1e-3));561 vel[ix] = (vel[ix] + ox * stiffness * dt) * damping;562 vel[ix + 1] = (vel[ix + 1] + oy * stiffness * dt + loose * 6 * fontSize * dt) * damping;563 vel[ix + 2] = (vel[ix + 2] - z * stiffness * dt) * damping;564 x += vel[ix] * dt;565 y += vel[ix + 1] * dt;566 z += vel[ix + 2] * dt;567 pos[ix] = x;568 pos[ix + 1] = y;569 pos[ix + 2] = z;570571 // At rest the wall breathes a little; loose blocks tumble572 const breathe = reducedMotion ? 0 : Math.sin(t * 1.6 + hx * 2.5 + hy * 1.5) * sample.cell * 0.18;573 dummy.position.set(x, y, z + breathe);574 dummy.quaternion.setFromAxisAngle(tmpAxis.set(axis[ix], axis[ix + 1], axis[ix + 2]), loose * 4 + seed[i] * loose * 6);575 dummy.scale.setScalar(1 - loose * 0.25);576 dummy.updateMatrix();577 m.setMatrixAt(i, dummy.matrix);578 m.setColorAt(i, tint.copy(base).lerp(hot, loose));579 }580 m.instanceMatrix.needsUpdate = true;581 if (m.instanceColor) m.instanceColor.needsUpdate = true;582 });583584 return (585 <FitToView size={[sample.width, sample.height]} maxHeight={0.7}>586 {/* Keyed on the sample: a new text rebuilds the instance buffers at the right size */}587 <instancedMesh key={sample.count + text} ref={mesh} args={[geometry, material, sample.count]} frustumCulled={false} />588 </FitToView>589 );590});591592const tmpAxis = new THREE.Vector3();593594/**595 * Text built out of thousands of small blocks floating on a wall. The cursor blows them off as it596 * sweeps through, they drift upward (inverse gravity) and snap back into the letters; a click sends597 * a shockwave through the whole word.598 */599function KineticGravityText3D({600 text,601 particleShape = "cube",602 cursorRadius,603 dispersalRadius = cursorRadius ?? 0.7,604 fontSize = 1.4,605 primaryColor,606 color = primaryColor ?? "#e4e4e7",607 density = 26,608 fontFamily,609 pauseWhenOffscreen,610 lowPowerMode,611}: KineticGravityTextProps) {612 return (613 <TypeCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} label={text} camera={{ position: [0, 0, 6], fov: 40 }}>614 <ambientLight intensity={0.4} />615 <directionalLight position={[3, 4, 5]} intensity={2.2} />616 <directionalLight position={[-4, -1, 2]} intensity={0.8} color="#a5b4fc" />617 <Environment resolution={256}>618 <Lightformer form="rect" intensity={2} position={[0, 4, 3]} scale={[8, 2, 1]} />619 <Lightformer form="rect" intensity={1} position={[-5, 0, 2]} scale={[2, 6, 1]} />620 <Lightformer form="ring" intensity={1.5} position={[4, -2, 3]} scale={2} />621 </Environment>622 <Blocks623 text={text}624 particleShape={particleShape}625 dispersalRadius={dispersalRadius}626 fontSize={fontSize}627 color={color}628 density={density}629 fontFamily={fontFamily}630 />631 </TypeCanvas>632 );633}634635export default memo(KineticGravityText3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import KineticGravityText3D from "@/components/KineticGravityText3D";23export default function Section() {4 return (5 // The component fills this box: give it a position and a height6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>7 <KineticGravityText3D8 text="KINETIC"9 particleShape="cube"10 cursorRadius={0.7}11 fontSize={1.4}12 density={26}13 primaryColor="#e4e4e7"14 />15 </div>16 );17}