← All components Next componentArchitect Compass→
Cursors · Audio
Audio Waveform
A ring of spectrum bars around the pointer, on a synthetic beat or the live microphone.
Move over the words, then the buttons.
Read the docsdata-cursor-text
<AudioWaveformCursor />Live
Move faster: the beat speeds up
Customize
Bars#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 audio-waveform
01
Install
The 3D packages this component is built on.
Nothing to install: React is all it needs.
02
Add the component
One self-contained file: create components/AudioWaveformCursor.tsx and paste it in.
components/AudioWaveformCursor.tsx
1"use client";23import { memo, useEffect, useRef, useState, type CSSProperties, type RefObject } from "react";45/** What counts as interactive: the cursors react when the pointer is over one of these. */6const INTERACTIVE_SELECTOR =7 "a, button, [role='button'], input, select, textarea, label, summary, [data-cursor], [data-cursor-text], [data-cursor-hover]";89/** Full-viewport, click-through layer above the page. */10const OVERLAY_STYLE: CSSProperties = {11 position: "fixed",12 top: 0,13 left: 0,14 width: "100vw",15 height: "100vh",16 pointerEvents: "none",17 zIndex: 9999,18};1920/**21 * False on touch screens (`pointer: coarse`) and during server rendering: the custom cursor is not22 * drawn and the native cursor is left alone. Follows the media query live (tablet + mouse…).23 */24function useCursorEnabled() {25 const [enabled, setEnabled] = useState(false);26 useEffect(() => {27 const query = window.matchMedia("(pointer: coarse)");28 const sync = () => setEnabled(!query.matches);29 sync();30 query.addEventListener("change", sync);31 return () => query.removeEventListener("change", sync);32 }, []);33 return enabled;34}3536function usePrefersReducedMotion() {37 const [reduced, setReduced] = useState(false);38 useEffect(() => {39 const query = window.matchMedia("(prefers-reduced-motion: reduce)");40 const sync = () => setReduced(query.matches);41 sync();42 query.addEventListener("change", sync);43 return () => query.removeEventListener("change", sync);44 }, []);45 return reduced;46}4748/** Hides the system cursor on the whole page while `active` (restored on unmount). */49function useHideNativeCursor(active: boolean) {50 useEffect(() => {51 if (!active) return undefined;52 const style = document.createElement("style");53 style.setAttribute("data-custom-cursor", "");54 style.textContent = "*, *::before, *::after { cursor: none !important; }";55 document.head.appendChild(style);56 return () => style.remove();57 }, [active]);58}5960interface CursorPointer {61 /** Position in CSS pixels, relative to the viewport. */62 x: number;63 y: number;64 /** Smoothed velocity, in CSS pixels per second. */65 vx: number;66 vy: number;67 speed: number;68 /** False until the first move, and while the pointer is outside the window. */69 visible: boolean;70 down: boolean;71 /** The interactive element under the pointer (closest match of the selector), or null. */72 target: HTMLElement | null;73 /** Incremented on every press, to trigger click effects. */74 clicks: number;75}7677/**78 * Tracks the pointer through window listeners and returns a ref read inside the animation loop:79 * moving the mouse never re-renders React. All listeners are removed on unmount.80 */81function useCursorPointer(enabled: boolean, selector = INTERACTIVE_SELECTOR): RefObject<CursorPointer> {82 const pointer = useRef<CursorPointer>({ x: -100, y: -100, vx: 0, vy: 0, speed: 0, visible: false, down: false, target: null, clicks: 0 });8384 useEffect(() => {85 if (!enabled) return undefined;86 let last = performance.now();87 const p = pointer.current;88 const pick = (event: PointerEvent) => {89 const el = event.target instanceof Element ? event.target.closest(selector) : null;90 p.target = el instanceof HTMLElement ? el : null;91 };92 const move = (event: PointerEvent) => {93 if (event.pointerType === "touch") return;94 const now = performance.now();95 const dt = Math.max(1, now - last) / 1000;96 last = now;97 if (p.visible) {98 // Smoothed: one jittery event must not make the effects jump99 p.vx = p.vx * 0.6 + ((event.clientX - p.x) / dt) * 0.4;100 p.vy = p.vy * 0.6 + ((event.clientY - p.y) / dt) * 0.4;101 }102 p.x = event.clientX;103 p.y = event.clientY;104 p.visible = true;105 pick(event);106 };107 const down = (event: PointerEvent) => {108 if (event.pointerType === "touch") return;109 p.down = true;110 p.clicks += 1;111 pick(event);112 };113 const up = () => {114 p.down = false;115 };116 const leave = () => {117 p.visible = false;118 p.down = false;119 };120 window.addEventListener("pointermove", move, { passive: true });121 window.addEventListener("pointerdown", down, { passive: true });122 window.addEventListener("pointerup", up, { passive: true });123 document.documentElement.addEventListener("pointerleave", leave);124 window.addEventListener("blur", leave);125 return () => {126 window.removeEventListener("pointermove", move);127 window.removeEventListener("pointerdown", down);128 window.removeEventListener("pointerup", up);129 document.documentElement.removeEventListener("pointerleave", leave);130 window.removeEventListener("blur", leave);131 };132 }, [enabled, selector]);133134 return pointer;135}136137/**138 * requestAnimationFrame loop: `frame(dt, time)` runs every frame (dt in seconds, capped) while139 * `enabled`; the browser pauses it in background tabs. The latest callback is always used.140 */141function useAnimationFrame(enabled: boolean, frame: (dt: number, time: number) => void) {142 const frameRef = useRef(frame);143 useEffect(() => {144 frameRef.current = frame;145 });146 useEffect(() => {147 if (!enabled) return undefined;148 let id = 0;149 let last = performance.now();150 const tick = (now: number) => {151 const dt = Math.min((now - last) / 1000, 1 / 20);152 last = now;153 frameRef.current(dt, now / 1000);154 id = requestAnimationFrame(tick);155 };156 id = requestAnimationFrame(tick);157 return () => cancelAnimationFrame(id);158 }, [enabled]);159}160161/**162 * Velocity only changes on pointer events: call this once per frame so it fades out when the pointer163 * stops, and read `speed` afterwards.164 */165function settlePointer(p: CursorPointer, dt: number) {166 const k = Math.exp(-10 * dt);167 p.vx *= k;168 p.vy *= k;169 p.speed = Math.hypot(p.vx, p.vy);170}171172/** Exponential smoothing factor for a frame: frame-rate independent `lerp`. */173const damp = (lambda: number, dt: number) => 1 - Math.exp(-lambda * dt);174175/**176 * Full-viewport 2D canvas sized to the window (pixel ratio capped at 2) and kept in sync on resize.177 * Returns the canvas ref; read `canvas.getContext("2d")` in the loop. Draw in CSS pixels.178 */179function useViewportCanvas(enabled: boolean) {180 const ref = useRef<HTMLCanvasElement>(null);181 useEffect(() => {182 if (!enabled) return undefined;183 const canvas = ref.current;184 if (!canvas) return undefined;185 const resize = () => {186 const dpr = Math.min(window.devicePixelRatio || 1, 2);187 canvas.width = Math.round(window.innerWidth * dpr);188 canvas.height = Math.round(window.innerHeight * dpr);189 canvas.getContext("2d")?.setTransform(dpr, 0, 0, dpr, 0, 0);190 };191 resize();192 window.addEventListener("resize", resize);193 return () => window.removeEventListener("resize", resize);194 }, [enabled]);195 return ref;196}197198/** Clears a canvas drawn in CSS pixels. */199function clearCanvas(ctx: CanvasRenderingContext2D) {200 ctx.save();201 ctx.setTransform(1, 0, 0, 1, 0, 0);202 ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);203 ctx.restore();204}205206/** "#rrggbb" (or "#rgb") to "r, g, b", for rgba() strings. */207function hexToRgb(hex: string) {208 let h = hex.replace("#", "");209 if (h.length === 3) h = h.split("").map((c) => c + c).join("");210 const n = parseInt(h.slice(0, 6), 16);211 if (Number.isNaN(n)) return "255, 255, 255";212 return `${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}`;213}214215/** 4. Rendering, materials and glow. */216interface MaterialProps {217 /** Main color of the object. Default "#6366f1". */218 primaryColor?: string;219 /** Color of the glow. Default "#00f0ff". */220 emissiveColor?: string;221 /** Strength of the glow, 0 (none) to 3. Default 1. */222 emissiveIntensity?: number;223 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */224 roughness?: number;225 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */226 metalness?: number;227 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */228 transmission?: number;229 /** Technical wireframe rendering. Default false. */230 wireframe?: boolean;231}232233export interface AudioWaveformCursorProps extends Pick<MaterialProps, "primaryColor"> {234 /** Number of spectrum bars around the ring. Default 32. */235 barCount?: number;236 primaryColor?: string;237 /** @deprecated Use `primaryColor`. */238 barColor?: string;239 /**240 * Drive the bars with the microphone: the browser asks for permission on the first click on the241 * page. Until then (or if refused) the bars follow a synthetic beat and the pointer's speed.242 * Default false.243 */244 audioReactive?: boolean;245 /** Radius of the ring, in CSS pixels. Default 18. */246 size?: number;247 /** Hide the system cursor while the ring is shown. Default true. */248 hideNativeCursor?: boolean;249}250251/**252 * A ring of spectrum bars around the pointer, oscillating like an audio visualiser — on a synthetic253 * beat that quickens with the pointer's speed, or on the live microphone with `audioReactive`.254 */255function AudioWaveformCursor({ barCount = 32, primaryColor, barColor = primaryColor ?? "#f0abfc", audioReactive = false, size = 18, hideNativeCursor = true }: AudioWaveformCursorProps) {256 const enabled = useCursorEnabled();257 const reducedMotion = usePrefersReducedMotion();258 const pointer = useCursorPointer(enabled);259 useHideNativeCursor(enabled && hideNativeCursor);260 const canvas = useViewportCanvas(enabled);261 const state = useRef({ x: -100, y: -100, levels: new Float32Array(128), energy: 0, hover: 0 });262 const audio = useRef<{ context: AudioContext; analyser: AnalyserNode; data: Uint8Array<ArrayBuffer>; stream: MediaStream } | null>(null);263264 // Microphone, asked for on the first click (browsers require a user gesture), released on unmount265 useEffect(() => {266 if (!enabled || !audioReactive) return undefined;267 let cancelled = false;268 const start = async () => {269 window.removeEventListener("pointerdown", start);270 try {271 const stream = await navigator.mediaDevices.getUserMedia({ audio: true });272 if (cancelled) {273 stream.getTracks().forEach((t) => t.stop());274 return;275 }276 const context = new AudioContext();277 const analyser = context.createAnalyser();278 analyser.fftSize = 256;279 analyser.smoothingTimeConstant = 0.75;280 context.createMediaStreamSource(stream).connect(analyser);281 audio.current = { context, analyser, data: new Uint8Array(analyser.frequencyBinCount), stream };282 } catch {283 // Refused or unavailable: the synthetic beat goes on284 }285 };286 window.addEventListener("pointerdown", start);287 return () => {288 cancelled = true;289 window.removeEventListener("pointerdown", start);290 const a = audio.current;291 if (a) {292 a.stream.getTracks().forEach((t) => t.stop());293 a.context.close();294 audio.current = null;295 }296 };297 }, [enabled, audioReactive]);298299 useAnimationFrame(enabled, (dt, time) => {300 const ctx = canvas.current?.getContext("2d");301 if (!ctx) return;302 const p = pointer.current;303 settlePointer(p, dt);304 const s = state.current;305 clearCanvas(ctx);306 if (!p.visible) return;307 s.x += (p.x - s.x) * damp(22, dt);308 s.y += (p.y - s.y) * damp(22, dt);309 s.energy += (Math.min(p.speed / 1500, 1) - s.energy) * damp(4, dt);310 s.hover += ((p.target ? 1 : 0) - s.hover) * damp(8, dt);311312 const count = Math.max(8, Math.min(Math.round(barCount), 128));313 const a = audio.current;314 if (a) a.analyser.getByteFrequencyData(a.data);315 const motion = reducedMotion ? 0.3 : 1;316 const beat = Math.pow(Math.max(0, Math.sin(time * (4 + s.energy * 6))), 8);317 for (let i = 0; i < count; i++) {318 let level: number;319 if (a) {320 // Mirror the spectrum around the ring: bass at the top and bottom, highs on the sides321 const u = i / count;322 const bin = Math.floor(Math.abs(u * 2 - 1) * a.data.length * 0.6);323 level = a.data[bin] / 255;324 } else {325 const phase = (i / count) * Math.PI * 2;326 level =327 (0.25 + 0.2 * Math.sin(phase * 3 + time * 3.1) + 0.15 * Math.sin(phase * 5 - time * 4.7)) * (0.5 + s.energy) * motion +328 beat * 0.35 * motion;329 }330 s.levels[i] += (Math.max(0, level) - s.levels[i]) * damp(a ? 20 : 12, dt);331 }332333 const rgb = hexToRgb(barColor);334 const radius = size * (1 + s.hover * 0.6) * (p.down ? 0.85 : 1);335 ctx.lineCap = "round";336 ctx.lineWidth = Math.max(1.5, (Math.PI * 2 * radius) / count * 0.45);337 ctx.shadowColor = `rgba(${rgb}, 0.8)`;338 ctx.shadowBlur = 6;339 for (let i = 0; i < count; i++) {340 const angle = (i / count) * Math.PI * 2 - Math.PI / 2;341 const len = 3 + s.levels[i] * size * 1.4;342 const c = Math.cos(angle);343 const sn = Math.sin(angle);344 ctx.strokeStyle = `rgba(${rgb}, ${0.55 + s.levels[i] * 0.45})`;345 ctx.beginPath();346 ctx.moveTo(s.x + c * radius, s.y + sn * radius);347 ctx.lineTo(s.x + c * (radius + len), s.y + sn * (radius + len));348 ctx.stroke();349 }350 ctx.shadowBlur = 0;351 ctx.fillStyle = `rgba(${rgb}, 1)`;352 ctx.beginPath();353 ctx.arc(p.x, p.y, 2.5, 0, Math.PI * 2);354 ctx.fill();355 });356357 if (!enabled) return null;358 return <canvas ref={canvas} aria-hidden="true" style={OVERLAY_STYLE} />;359}360361export default memo(AudioWaveformCursor);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import AudioWaveformCursor from "@/components/AudioWaveformCursor";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 <AudioWaveformCursor8 barCount={32}9 size={18}10 primaryColor="#f0abfc"11 audioReactive={false}12 />13 </div>14 );15}