Loading…
← All components

Typography · Voxels

Voxel Audio Text

Your text as a grid of voxel columns that rise under the cursor — or dance to the frequencies of a track you pass in.

<VoxelAudioText3D />Live

Customize

Low#312e81
High#f0abfc

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add voxel-audio
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber && npm install -D @types/three
02

Add the component

One self-contained file: create components/VoxelAudioText3D.tsx and paste it in.

components/VoxelAudioText3D.tsx
1"use client";
2
3import {
4 Component,
5 memo,
6 Suspense,
7 useCallback,
8 useEffect,
9 useLayoutEffect,
10 useMemo,
11 useRef,
12 useState,
13 type CSSProperties,
14 type ReactNode,
15 type RefObject,
16} from "react";
17import * as THREE from "three";
18import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";
19
20/**
21 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
22 * their own tailored scenes).
23 *
24 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
25 * 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 are
31 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
32 */
33
34/** 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";
36
37/** 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}
48
49/** 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}
60
61/** 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}
74
75/** 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}
92
93/** 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}
104
105/** 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}
114
115/** 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}
124
125/** Every group at once. Components extend only the groups they apply (see the top of this file). */
126interface Base3DComponentProps
127 extends CursorProps,
128 TiltProps,
129 Text3DProps,
130 MaterialProps,
131 MotionProps,
132 EnvironmentProps,
133 PerformanceProps {}
134
135type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
136
137/** 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};
166
167/** Fills the positioned parent and receives pointer events. */
168const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
169
170/** 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};
182
183interface 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}
190
191/**
192 * Ready-to-use <Canvas> shared by the typography components: fills its positioned parent, pauses
193 * its render loop while scrolled out of view, exposes the text to screen readers, and R3F disposes
194 * 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);
199
200 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 }, []);
207
208 return (
209 <div ref={containerRef} style={FILL_STYLE}>
210 <span style={SR_ONLY}>{label}</span>
211 <Canvas
212 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}
227
228class 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}
237
238function 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}
249
250interface 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}
258
259/**
260 * Tracks the pointer relative to the canvas through window listeners, so HTML laid over the canvas
261 * 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 });
266
267 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]);
294
295 return pointer;
296}
297
298const plane = new THREE.Plane();
299
300const raycaster = new THREE.Raycaster();
301
302/** 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}
308
309interface 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}
320
321/**
322 * Scales its content down (never up) so that a long text still fits the canvas, on every size and
323 * 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);
330
331 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 1
338 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]);
343
344 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 });
350
351 return (
352 <group ref={outer}>
353 <group ref={inner}>{children}</group>
354 </group>
355 );
356}
357
358/** 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}
363
364interface 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}
373
374/**
375 * Rasterizes the text with a 2D canvas (any font the page has, every character) and returns the
376 * centers of the filled cells of a grid with `rows` cells per line height, scaled so a line is
377 * `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 cell
382 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)));
395
396 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 cell
404 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}
411
412export interface VoxelAudioTextProps extends Pick<Text3DProps, "text">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
413 text: string;
414 /** Size of one voxel in world units: smaller voxels, finer letters. Default 0.08. */
415 voxelSize?: number;
416 /** Height of the tallest columns, in letter heights. Default 0.6. */
417 maxElevation?: number;
418 /** Color of the low and of the high columns. Default ["#312e81", "#f0abfc"]. */
419 colorGradient?: [string, string];
420 /** A track to play: the columns then follow its frequencies (a play button appears). */
421 audioUrl?: string;
422 /** CSS font the letters are drawn with. Default: the page's font. */
423 fontFamily?: string;
424}
425
426const LINE_HEIGHT = 1.4;
427const MAX_VOXELS = 7000;
428
429/** Web Audio analyser for a track, created on the first play (browsers require a user gesture). */
430function useAudioAnalyser(audioUrl?: string) {
431 const [playing, setPlaying] = useState(false);
432 const audio = useRef<{ element: HTMLAudioElement; context: AudioContext; analyser: AnalyserNode; data: Uint8Array<ArrayBuffer> } | null>(null);
433
434 useEffect(
435 () => () => {
436 const a = audio.current;
437 if (!a) return;
438 a.element.pause();
439 a.element.src = "";
440 a.context.close();
441 audio.current = null;
442 },
443 [audioUrl]
444 );
445
446 const toggle = useCallback(async () => {
447 if (!audioUrl) return;
448 if (!audio.current) {
449 const element = new Audio(audioUrl);
450 element.crossOrigin = "anonymous";
451 element.loop = true;
452 const context = new AudioContext();
453 const analyser = context.createAnalyser();
454 analyser.fftSize = 256;
455 analyser.smoothingTimeConstant = 0.78;
456 context.createMediaElementSource(element).connect(analyser);
457 analyser.connect(context.destination);
458 audio.current = { element, context, analyser, data: new Uint8Array(analyser.frequencyBinCount) };
459 }
460 const a = audio.current;
461 if (a.element.paused) {
462 await a.context.resume();
463 await a.element.play().catch(() => undefined);
464 setPlaying(!a.element.paused);
465 } else {
466 a.element.pause();
467 setPlaying(false);
468 }
469 }, [audioUrl]);
470
471 return { playing, toggle, audio };
472}
473
474type VoxelsProps = Required<Omit<VoxelAudioTextProps, "pauseWhenOffscreen" | "lowPowerMode" | "audioUrl" | "fontFamily">> & {
475 fontFamily?: string;
476 audio: ReturnType<typeof useAudioAnalyser>["audio"];
477 playing: boolean;
478};
479
480const Voxels = memo(function Voxels({ text, voxelSize, maxElevation, colorGradient, fontFamily, audio, playing }: VoxelsProps) {
481 const reducedMotion = usePrefersReducedMotion();
482 const pointer = useCanvasPointer();
483 const mesh = useRef<THREE.InstancedMesh>(null);
484 const hit = useRef(new THREE.Vector3(1e6, 1e6, 0));
485
486 const sample = useMemo(() => {
487 let rows = THREE.MathUtils.clamp(Math.round(LINE_HEIGHT / voxelSize), 6, 48);
488 let result = sampleText(text, { rows, lineHeight: LINE_HEIGHT, fontFamily });
489 while (result.count > MAX_VOXELS && rows > 6) {
490 rows -= 2;
491 result = sampleText(text, { rows, lineHeight: LINE_HEIGHT, fontFamily });
492 }
493 return result;
494 }, [text, voxelSize, fontFamily]);
495
496 // A unit-tall column standing on z = 0: scaling it on z raises it toward the viewer
497 const geometry = useMemo(() => {
498 const g = new THREE.BoxGeometry(sample.cell * 0.88, sample.cell * 0.88, 1);
499 g.translate(0, 0, 0.5);
500 return g;
501 }, [sample.cell]);
502 const material = useMemo(() => new THREE.MeshStandardMaterial({ roughness: 0.38, metalness: 0.2 }), []);
503 useEffect(() => () => geometry.dispose(), [geometry]);
504 useEffect(() => () => material.dispose(), [material]);
505
506 const low = useMemo(() => new THREE.Color(colorGradient[0]), [colorGradient]);
507 const high = useMemo(() => new THREE.Color(colorGradient[1]), [colorGradient]);
508 const heights = useMemo(() => new Float32Array(sample.count), [sample]);
509 const dummy = useMemo(() => new THREE.Object3D(), []);
510 const tint = useMemo(() => new THREE.Color(), []);
511 const time = useRef(0);
512 const hover = useRef(0);
513
514 useFrame((frame, delta) => {
515 const m = mesh.current;
516 if (!m) return;
517 const dt = Math.min(delta, 1 / 30);
518 time.current += dt * (reducedMotion ? 0.25 : 1);
519 const t = time.current;
520
521 const p = pointer.current;
522 if (p.inside) {
523 pointerOnPlane(p.ndc, frame.camera, hit.current);
524 m.worldToLocal(hit.current);
525 }
526 hover.current = THREE.MathUtils.damp(hover.current, p.inside ? 1 : 0, 3, dt);
527
528 const a = playing ? audio.current : null;
529 if (a) a.analyser.getByteFrequencyData(a.data);
530 const bins = a ? a.data.length * 0.7 : 0; // the top of the spectrum is mostly empty
531
532 const peak = maxElevation * LINE_HEIGHT;
533 const base = sample.cell * 0.6;
534 const halfWidth = sample.width / 2;
535 for (let i = 0; i < sample.count; i++) {
536 const x = sample.points[i * 2];
537 const y = sample.points[i * 2 + 1];
538 // Idle: a slow swell rolling across the word
539 let level = (Math.sin(t * 1.8 - x * 2.2) * 0.5 + 0.5) * 0.18 + (Math.sin(t * 1.1 + y * 3) * 0.5 + 0.5) * 0.06;
540 // Pointer: a raised mound under the cursor, with a ripple around it
541 const d = Math.hypot(x - hit.current.x, y - hit.current.y);
542 level += hover.current * (Math.exp(-d * d * 3.2) * 0.85 + Math.sin(d * 9 - t * 7) * Math.exp(-d * 1.6) * 0.12);
543 // Audio: each column follows the frequency band of its horizontal position (bass on the left)
544 if (a) {
545 const u = (x + halfWidth) / Math.max(sample.width, 1e-3);
546 const bin = Math.min(bins - 1, Math.floor(Math.pow(u, 1.6) * bins));
547 level = level * 0.4 + (a.data[bin] / 255) * (0.75 + 0.25 * Math.sin(y * 6 + t * 3));
548 }
549 level = THREE.MathUtils.clamp(level, 0, 1);
550 heights[i] = THREE.MathUtils.damp(heights[i], level, a ? 18 : 8, dt);
551 const h = heights[i];
552
553 dummy.position.set(x, y, 0);
554 dummy.scale.set(1, 1, base + h * peak);
555 dummy.updateMatrix();
556 m.setMatrixAt(i, dummy.matrix);
557 m.setColorAt(i, tint.copy(low).lerp(high, Math.min(1, h * 1.3)));
558 }
559 m.instanceMatrix.needsUpdate = true;
560 if (m.instanceColor) m.instanceColor.needsUpdate = true;
561
562 // Seen from slightly below and aside, so the columns show their height; the pointer steers the view
563 const camera = frame.camera;
564 camera.position.x = THREE.MathUtils.damp(camera.position.x, (p.inside ? p.ndc.x : 0) * 1.4, 2, dt);
565 camera.position.y = THREE.MathUtils.damp(camera.position.y, -3.3 + (p.inside ? p.ndc.y : 0) * 0.8, 2, dt);
566 camera.lookAt(0, 0, 0.3);
567 });
568
569 return (
570 <FitToView size={[sample.width, sample.height]} maxWidth={0.84} maxHeight={0.58}>
571 <instancedMesh key={sample.count + text} ref={mesh} args={[geometry, material, sample.count]} frustumCulled={false} />
572 </FitToView>
573 );
574});
575
576/**
577 * Text made of a grid of voxel columns that rise and fall: a swell at rest, a mound that follows the
578 * cursor, and — given an `audioUrl` — the live frequencies of the track, bass on the left.
579 */
580function VoxelAudioText3D({
581 text,
582 voxelSize = 0.08,
583 maxElevation = 0.6,
584 colorGradient = ["#312e81", "#f0abfc"],
585 audioUrl,
586 fontFamily,
587 pauseWhenOffscreen,
588 lowPowerMode,
589}: VoxelAudioTextProps) {
590 const { playing, toggle, audio } = useAudioAnalyser(audioUrl);
591
592 const overlay = audioUrl ? (
593 <button
594 type="button"
595 onClick={toggle}
596 aria-pressed={playing}
597 style={{
598 position: "absolute",
599 left: "50%",
600 bottom: 24,
601 transform: "translateX(-50%)",
602 padding: "10px 18px",
603 borderRadius: 999,
604 border: "1px solid rgba(255,255,255,0.25)",
605 background: "rgba(0,0,0,0.55)",
606 color: "#fff",
607 font: "600 13px/1 system-ui, sans-serif",
608 cursor: "pointer",
609 backdropFilter: "blur(8px)",
610 }}
611 >
612 {playing ? "❚❚ Pause" : "▶ Play the track"}
613 </button>
614 ) : null;
615
616 return (
617 <TypeCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} label={text} overlay={overlay} camera={{ position: [0, -3.3, 4.6], fov: 40 }}>
618 <ambientLight intensity={0.55} />
619 <directionalLight position={[-3, 2, 6]} intensity={1.8} />
620 <directionalLight position={[4, -3, 2]} intensity={0.5} color="#a5b4fc" />
621 <Voxels
622 text={text}
623 voxelSize={voxelSize}
624 maxElevation={maxElevation}
625 colorGradient={colorGradient}
626 fontFamily={fontFamily}
627 audio={audio}
628 playing={playing}
629 />
630 </TypeCanvas>
631 );
632}
633
634export default memo(VoxelAudioText3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import VoxelAudioText3D from "@/components/VoxelAudioText3D";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <VoxelAudioText3D
8 text="VOXEL"
9 voxelSize={0.08}
10 maxElevation={0.6}
11 colorGradient={["#312e81", "#f0abfc"]}
12 />
13 </div>
14 );
15}
Next componentMonolith Shadow→