← All components Next componentReward Modal→
Widgets · Data
Interactive Chart
An extruded donut or bar chart in smoked glass: the hovered slice slides out with its value in a tooltip.
<InteractiveChart3D />Live
Hover a slice or a bar
Customize
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add interactive-chart
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/InteractiveChart3D.tsx and paste it in.
components/InteractiveChart3D.tsx
1"use client";23import {4 memo,5 useEffect,6 useMemo,7 useRef,8 useState,9 type CSSProperties,10 type ReactNode,11 type RefObject,12} from "react";13import * as THREE from "three";14import { Canvas, useFrame, useThree, type CanvasProps } from "@react-three/fiber";15import { ContactShadows, Environment, Lightformer, OrbitControls } from "@react-three/drei";1617/**18 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep19 * their own tailored scenes).20 *21 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its22 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):23 *24 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }25 *26 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,27 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are28 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.29 */3031/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */32export type TiltAxis = "both" | "x-only" | "y-only" | "none";3334/** 1. Cursor: how the pointer pulls, pushes and drags the object. */35interface CursorProps {36 /** 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). */37 cursorRadius?: number;38 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */39 cursorForce?: number;40 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */41 magneticStrength?: number;42 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */43 cursorDamping?: number;44}4546/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */47interface TiltProps {48 /** Largest lean towards the pointer, in degrees. Default 15. */49 maxTiltAngle?: number;50 /** Axes that follow the pointer. Default "both". */51 tiltAxis?: TiltAxis;52 /** Lean away from the pointer instead of towards it. Default false. */53 invertTilt?: boolean;54 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */55 parallaxOffset?: number;56}5758/** 3. Text and 3D typography, for components that draw a label. */59interface Text3DProps {60 /** The label drawn by the component. */61 text?: string;62 /** Scale of the lettering. Default 1. */63 fontSize?: number;64 /** Extrusion depth of 3D letters. Default 0.2. */65 textDepth?: number;66 /** Bevelled, light-catching edges on 3D letters. Default true. */67 bevelEnabled?: boolean;68 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */69 fontUrl?: string;70}7172/** 4. Rendering, materials and glow. */73interface MaterialProps {74 /** Main color of the object. Default "#6366f1". */75 primaryColor?: string;76 /** Color of the glow. Default "#00f0ff". */77 emissiveColor?: string;78 /** Strength of the glow, 0 (none) to 3. Default 1. */79 emissiveIntensity?: number;80 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */81 roughness?: number;82 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */83 metalness?: number;84 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */85 transmission?: number;86 /** Technical wireframe rendering. Default false. */87 wireframe?: boolean;88}8990/** 5. Particles, idle motion and shader animation. */91interface MotionProps {92 /** Number of instanced elements. Default depends on the component. */93 particleCount?: number;94 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */95 autoRotateSpeed?: number;96 /** Pulses or ripples per second. Default 1. */97 pulseRate?: number;98 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */99 displacementScale?: number;100}101102/** 6. Environment and camera. */103interface EnvironmentProps {104 /** Camera field of view, in degrees. Default depends on the component. */105 cameraFov?: number;106 /** Color of the depth fog. Default "#0a0a0a". */107 fogColor?: string;108 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */109 fogDensity?: number;110}111112/** 7. Performance and accessibility. */113interface PerformanceProps {114 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */115 lowPowerMode?: boolean;116 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */117 respectReducedMotion?: boolean;118 /** Stop the render loop while the component is scrolled out of view. Default true. */119 pauseWhenOffscreen?: boolean;120}121122/** Every group at once. Components extend only the groups they apply (see the top of this file). */123interface Base3DComponentProps124 extends CursorProps,125 TiltProps,126 Text3DProps,127 MaterialProps,128 MotionProps,129 EnvironmentProps,130 PerformanceProps {}131132type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;133134/** The values a prop takes when it is left out. A component may override one, and then documents it. */135const DEFAULT_3D_PROPS: Defaults = {136 cursorRadius: 220,137 cursorForce: 1,138 magneticStrength: 0,139 cursorDamping: 0.1,140 maxTiltAngle: 15,141 tiltAxis: "both",142 invertTilt: false,143 parallaxOffset: 1,144 fontSize: 1,145 textDepth: 0.2,146 bevelEnabled: true,147 primaryColor: "#6366f1",148 emissiveColor: "#00f0ff",149 emissiveIntensity: 1,150 roughness: 0.3,151 metalness: 0.5,152 transmission: 0,153 wireframe: false,154 autoRotateSpeed: 0,155 pulseRate: 1,156 displacementScale: 1,157 fogColor: "#0a0a0a",158 fogDensity: 0,159 lowPowerMode: false,160 respectReducedMotion: true,161 pauseWhenOffscreen: true,162};163164/** Fills the positioned parent. The objects receive pointer events (orbit, hover, click). */165const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };166167/** Styles shared by the HTML cards anchored in the scenes (drei <Html>). */168const CARD_STYLE: CSSProperties = {169 minWidth: 180,170 maxWidth: 240,171 borderRadius: 14,172 background: "rgba(10,10,14,0.86)",173 border: "1px solid rgba(255,255,255,0.14)",174 padding: "10px 12px",175 color: "white",176 font: "500 12px/1.45 system-ui, sans-serif",177 backdropFilter: "blur(8px)",178 boxShadow: "0 18px 40px -18px rgba(0,0,0,0.8)",179 pointerEvents: "auto",180};181182interface ObjectCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {183 children: ReactNode;184 /** CSS touch-action of the canvas: "pan-y" keeps vertical page scrolling on touch screens. */185 touchAction?: CSSProperties["touchAction"];186}187188/**189 * Ready-to-use <Canvas> shared by every object: fills its positioned parent, pauses its render loop190 * while scrolled out of view, caps the pixel ratio; R3F disposes the renderer on unmount.191 */192function ObjectCanvas({ children, touchAction = "pan-y", dpr = [1, 2], shadows, pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: ObjectCanvasProps) {193 const containerRef = useRef<HTMLDivElement>(null);194 const [inView, setInView] = useState(true);195196 useEffect(() => {197 const el = containerRef.current;198 if (!el) return undefined;199 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));200 observer.observe(el);201 return () => observer.disconnect();202 }, []);203204 return (205 <div ref={containerRef} style={FILL_STYLE}>206 <Canvas207 dpr={lowPowerMode ? 1 : dpr}208 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}209 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}210 style={{ touchAction }}211 // `shadows` alone asks R3F for PCFSoftShadowMap, which recent three.js versions removed (with a warning)212 shadows={shadows === true ? "percentage" : shadows}213 {...canvasProps}214 >215 {children}216 </Canvas>217 </div>218 );219}220221/** Studio reflections from light panels: no HDR file to download. */222function StudioEnvironment({ intensity = 1, warm = false }: { intensity?: number; warm?: boolean }) {223 return (224 <Environment resolution={256} frames={1}>225 <Lightformer form="rect" intensity={3 * intensity} position={[0, 5, 2]} rotation-x={Math.PI / 2} scale={[10, 3, 1]} />226 <Lightformer227 form="rect"228 intensity={2 * intensity}229 position={[-5, 1, 2]}230 rotation-y={Math.PI / 2}231 scale={[2, 6, 1]}232 color={warm ? "#ffe2c4" : "#ffffff"}233 />234 <Lightformer235 form="rect"236 intensity={1.5 * intensity}237 position={[5, 0, -2]}238 rotation-y={-Math.PI / 2}239 scale={[2, 6, 1]}240 color={warm ? "#c4dcff" : "#ffffff"}241 />242 <Lightformer form="ring" intensity={2 * intensity} position={[2, 3, 5]} scale={2} />243 </Environment>244 );245}246247/** Frame-rate independent exponential smoothing factor. */248const smoothing = (lambda: number, delta: number) => 1 - Math.exp(-lambda * Math.min(delta, 1 / 20));249250/**251 * Labels, pins and cards are plain DOM elements rendered next to the canvas (not drei <Html>, whose252 * per-label React roots misbehave on unmount under React 19). The scene moves them every frame.253 */254const OVERLAY_ANCHOR: CSSProperties = { position: "absolute", left: 0, top: 0, willChange: "transform", zIndex: 1 };255256const projected = new THREE.Vector3();257258/** Moves a DOM element onto the screen projection of a world-space point; hides it when off screen. */259function placeOverlay(el: HTMLElement | null, world: THREE.Vector3, camera: THREE.Camera, width: number, height: number) {260 if (!el) return false;261 projected.copy(world).project(camera);262 const x = (projected.x * 0.5 + 0.5) * width;263 const y = (-projected.y * 0.5 + 0.5) * height;264 // Hidden behind the camera or outside the canvas (it must not spill over the page around it)265 const visible = projected.z < 1 && x >= 0 && x <= width && y >= 0 && y <= height;266 el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0)`;267 el.style.visibility = visible ? "visible" : "hidden";268 return visible;269}270271/**272 * Keeps the object in frame on narrow canvases: when the aspect ratio drops below `minAspect`, the273 * camera backs away from `target` (the orbit target, if controls are set) proportionally. It only274 * acts when the canvas is resized, so it never fights the user's own orbiting.275 */276function ResponsiveCamera({ minAspect, target = [0, 0, 0] }: { minAspect: number; target?: [number, number, number] }) {277 const camera = useThree((state) => state.camera);278 const size = useThree((state) => state.size);279 const controls = useThree((state) => state.controls) as { target?: THREE.Vector3; update?: () => void } | null;280 const base = useRef<THREE.Vector3 | null>(null);281282 useEffect(() => {283 const center = controls?.target ?? new THREE.Vector3(...target);284 // The offset the scene was designed with, captured once285 if (!base.current) base.current = camera.position.clone().sub(center);286 const factor = Math.max(1, minAspect / (size.width / Math.max(size.height, 1)));287 camera.position.copy(center).addScaledVector(base.current, factor);288 controls?.update?.();289 // `target` is read once with the base offset; an inline array would otherwise re-run this every render290 }, [size.width, size.height, camera, controls, minAspect]);291292 return null;293}294295export interface ChartDatum {296 label: string;297 value: number;298 color: string;299}300301export interface InteractiveChartProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {302 data: ChartDatum[];303 /** Extruded donut ("pie") or bars. Default "pie". */304 chartType?: "pie" | "bar";305 /** Thickness of the pie, or depth of the bars, in world units. Default 0.5. */306 extrusionDepth?: number;307 /** Formats values in the tooltip and the legend. Default: the number as is. */308 formatValue?: (value: number) => string;309}310311const PIE = { inner: 0.62, outer: 1.7, gap: 0.025 };312const BAR = { width: 0.5, gap: 0.28, maxHeight: 2.4 };313314/* -------------------------------------------------------------------------- */315/* Geometry */316/* -------------------------------------------------------------------------- */317318/** Annular sector from a0 to a1 (radians), extruded upwards. */319function sliceGeometry(a0: number, a1: number, depth: number) {320 const s = new THREE.Shape();321 const g0 = a0 + PIE.gap / PIE.outer;322 const g1 = a1 - PIE.gap / PIE.outer;323 s.absarc(0, 0, PIE.outer, g0, g1, false);324 s.lineTo(Math.cos(a1 - PIE.gap / PIE.inner) * PIE.inner, Math.sin(a1 - PIE.gap / PIE.inner) * PIE.inner);325 s.absarc(0, 0, PIE.inner, a1 - PIE.gap / PIE.inner, a0 + PIE.gap / PIE.inner, true);326 s.closePath();327 const geometry = new THREE.ExtrudeGeometry(s, { depth, bevelEnabled: true, bevelThickness: 0.03, bevelSize: 0.03, bevelSegments: 3, curveSegments: 48 });328 // Lay it flat: the extrusion goes up329 geometry.rotateX(-Math.PI / 2);330 return geometry;331}332333interface Segment {334 geometry: THREE.BufferGeometry;335 /** Rest position and the direction it moves to when hovered. */336 base: THREE.Vector3;337 pop: THREE.Vector3;338 /** Where the tooltip is anchored (local to the chart). */339 anchor: THREE.Vector3;340}341342function buildSegments(data: ChartDatum[], chartType: "pie" | "bar", depth: number): Segment[] {343 const total = data.reduce((sum, d) => sum + Math.max(0, d.value), 0) || 1;344 if (chartType === "pie") {345 let a = Math.PI / 2;346 return data.map((d) => {347 const sweep = (Math.max(0, d.value) / total) * Math.PI * 2;348 const mid = a + sweep / 2;349 // Shape space (x, y) becomes world (x, -z) once laid flat350 const dir = new THREE.Vector3(Math.cos(mid), 0, -Math.sin(mid));351 const segment = {352 geometry: sliceGeometry(a, a + sweep, depth),353 base: new THREE.Vector3(),354 pop: dir.clone().multiplyScalar(0.22).add(new THREE.Vector3(0, 0.12, 0)),355 anchor: dir.clone().multiplyScalar((PIE.inner + PIE.outer) / 2).add(new THREE.Vector3(0, depth + 0.1, 0)),356 };357 a += sweep;358 return segment;359 });360 }361 const max = Math.max(...data.map((d) => d.value), 1e-6);362 const span = data.length * BAR.width + (data.length - 1) * BAR.gap;363 return data.map((d, i) => {364 const h = Math.max(0.04, (Math.max(0, d.value) / max) * BAR.maxHeight);365 const geometry = new THREE.BoxGeometry(BAR.width, h, depth, 1, 1, 1);366 geometry.translate(0, h / 2, 0);367 const x = -span / 2 + BAR.width / 2 + i * (BAR.width + BAR.gap);368 return { geometry, base: new THREE.Vector3(x, 0, 0), pop: new THREE.Vector3(0, 0.12, 0.25), anchor: new THREE.Vector3(x, h + 0.15, 0) };369 });370}371372/* -------------------------------------------------------------------------- */373/* Scene */374/* -------------------------------------------------------------------------- */375376interface ChartSceneProps {377 data: ChartDatum[];378 chartType: "pie" | "bar";379 depth: number;380 hovered: number;381 onHover: (i: number) => void;382 tooltip: RefObject<HTMLDivElement | null>;383}384385function ChartScene({ data, chartType, depth, hovered, onHover, tooltip }: ChartSceneProps) {386 const gl = useThree((s) => s.gl);387 const segments = useMemo(() => buildSegments(data, chartType, depth), [data, chartType, depth]);388 useEffect(() => () => segments.forEach((s) => s.geometry.dispose()), [segments]);389 // Smoked-glass look: clear coat, a little transmission, the datum's colour390 const materials = useMemo(391 () => data.map((d) => new THREE.MeshPhysicalMaterial({ color: d.color, roughness: 0.22, clearcoat: 1, clearcoatRoughness: 0.1, transmission: 0.25, thickness: 0.8, ior: 1.4, emissive: new THREE.Color(0, 0, 0) })),392 [data]393 );394 useEffect(() => () => materials.forEach((m) => m.dispose()), [materials]);395396 useEffect(() => {397 gl.domElement.style.cursor = hovered >= 0 ? "pointer" : "";398 }, [hovered, gl]);399400 const meshes = useRef<(THREE.Mesh | null)[]>([]);401 const chart = useRef<THREE.Group>(null);402 const scratch = useMemo(() => ({ target: new THREE.Vector3(), anchor: new THREE.Vector3(), glow: new THREE.Color() }), []);403404 useFrame((state, delta) => {405 const k = smoothing(10, delta);406 segments.forEach((s, i) => {407 const mesh = meshes.current[i];408 if (!mesh) return;409 // The hovered segment slides out of the chart and glows; the others dim slightly410 scratch.target.copy(s.base);411 if (i === hovered) scratch.target.add(s.pop);412 mesh.position.lerp(scratch.target, k);413 scratch.glow.set(data[i].color).multiplyScalar(i === hovered ? 0.35 : 0);414 materials[i].emissive.lerp(scratch.glow, k);415 });416 if (hovered >= 0 && chart.current && segments[hovered]) {417 scratch.anchor.copy(segments[hovered].anchor).add(segments[hovered].pop);418 chart.current.localToWorld(scratch.anchor);419 placeOverlay(tooltip.current, scratch.anchor, state.camera, state.size.width, state.size.height);420 }421 });422423 return (424 <group ref={chart} position={chartType === "pie" ? [0, -0.3, 0] : [0, -1.1, 0]}>425 {segments.map((s, i) => (426 <mesh427 key={`${chartType}-${i}`}428 ref={(el) => {429 meshes.current[i] = el;430 }}431 geometry={s.geometry}432 material={materials[i]}433 position={s.base}434 castShadow435 onPointerOver={(e) => {436 e.stopPropagation();437 onHover(i);438 }}439 onPointerOut={() => onHover(-1)}440 />441 ))}442 </group>443 );444}445446/**447 * Self-contained 3D chart: fills its positioned parent. Hover a slice or a bar (or a legend entry) to448 * pull it out and read its value; drag to turn the chart.449 */450function InteractiveChart3D({ data, chartType = "pie", extrusionDepth = 0.5, formatValue = (v) => String(v), pauseWhenOffscreen, lowPowerMode }: InteractiveChartProps) {451 const [hovered, setHovered] = useState(-1);452 const tooltip = useRef<HTMLDivElement>(null);453 const total = data.reduce((sum, d) => sum + Math.max(0, d.value), 0) || 1;454 const datum = hovered >= 0 ? data[hovered] : null;455 const camera = chartType === "pie" ? { position: [0, 4.4, 5.8] as [number, number, number], fov: 38 } : { position: [0, 1.8, 7.2] as [number, number, number], fov: 38 };456457 return (458 <>459 <ObjectCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} key={chartType} shadows camera={camera}>460 <ambientLight intensity={0.6} />461 <directionalLight position={[3, 6, 4]} intensity={1.6} castShadow shadow-mapSize={[1024, 1024]} />462 <StudioEnvironment intensity={0.8} />463 <OrbitControls makeDefault enableZoom={false} enablePan={false} enableDamping dampingFactor={0.08} minPolarAngle={0.35} maxPolarAngle={1.35} target={[0, 0, 0]} />464 <ResponsiveCamera minAspect={1.2} />465 <ChartScene data={data} chartType={chartType} depth={extrusionDepth} hovered={hovered} onHover={setHovered} tooltip={tooltip} />466 <ContactShadows position={[0, chartType === "pie" ? -0.31 : -1.11, 0]} opacity={0.4} scale={8} blur={2.4} far={3} resolution={512} />467 </ObjectCanvas>468469 {datum ? (470 <div ref={tooltip} style={{ ...OVERLAY_ANCHOR, visibility: "hidden", pointerEvents: "none" }}>471 <div style={{ ...CARD_STYLE, minWidth: 0, transform: "translate(-50%, calc(-100% - 10px))", whiteSpace: "nowrap" }} role="status">472 <div style={{ display: "flex", alignItems: "center", gap: 8 }}>473 <span style={{ width: 9, height: 9, borderRadius: 999, background: datum.color }} />474 <strong>{datum.label}</strong>475 </div>476 <div style={{ fontSize: 20, fontWeight: 700, marginTop: 4, fontVariantNumeric: "tabular-nums" }}>{formatValue(datum.value)}</div>477 <div style={{ opacity: 0.55 }}>{((Math.max(0, datum.value) / total) * 100).toFixed(1)} % of total</div>478 </div>479 </div>480 ) : null}481482 {/* Legend: also a keyboard- and screen-reader-friendly way to read the data */}483 <ul style={{ position: "absolute", left: 18, bottom: 18, margin: 0, padding: 0, listStyle: "none", display: "grid", gap: 6, color: "white", font: "500 12px/1.3 system-ui, sans-serif" }}>484 {data.map((d, i) => (485 <li key={`${d.label}-${i}`}>486 <button487 type="button"488 onMouseEnter={() => setHovered(i)}489 onMouseLeave={() => setHovered(-1)}490 onFocus={() => setHovered(i)}491 onBlur={() => setHovered(-1)}492 style={{ display: "flex", alignItems: "center", gap: 8, background: "none", border: 0, padding: 0, color: "inherit", cursor: "pointer", opacity: hovered < 0 || hovered === i ? 1 : 0.5 }}493 >494 <span style={{ width: 9, height: 9, borderRadius: 999, background: d.color }} />495 <span>{d.label}</span>496 <span style={{ opacity: 0.55, fontVariantNumeric: "tabular-nums" }}>{formatValue(d.value)}</span>497 </button>498 </li>499 ))}500 </ul>501 </>502 );503}504505export default memo(InteractiveChart3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import InteractiveChart3D from "@/components/InteractiveChart3D";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 <InteractiveChart3D8 extrusionDepth={0.5}9 />10 </div>11 );12}