← All components Next componentLiquid Slider→
Advanced · Data
Isometric City Chart
Data as a small isometric city: buildings rise into view, hovering one shows its figure.
<IsometricCityGrid3D />Live
Hover a building to read its value
Customize
Buildings#27272a
Highlight#a78bfa
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add city-grid
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/IsometricCityGrid3D.tsx and paste it in.
components/IsometricCityGrid3D.tsx
1"use client";23import {4 memo,5 useEffect,6 useLayoutEffect,7 useMemo,8 useRef,9 useState,10 type CSSProperties,11 type ReactNode,12} from "react";13import * as THREE from "three";14import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";15import { Canvas, useFrame, useThree, type CanvasProps, type ThreeEvent } from "@react-three/fiber";16import { Environment, Html, Lightformer } from "@react-three/drei";1718/**19 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep20 * their own tailored scenes).21 *22 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its23 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):24 *25 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }26 *27 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,28 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are29 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.30 */3132/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */33export type TiltAxis = "both" | "x-only" | "y-only" | "none";3435/** 1. Cursor: how the pointer pulls, pushes and drags the object. */36interface CursorProps {37 /** 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). */38 cursorRadius?: number;39 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */40 cursorForce?: number;41 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */42 magneticStrength?: number;43 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */44 cursorDamping?: number;45}4647/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */48interface TiltProps {49 /** Largest lean towards the pointer, in degrees. Default 15. */50 maxTiltAngle?: number;51 /** Axes that follow the pointer. Default "both". */52 tiltAxis?: TiltAxis;53 /** Lean away from the pointer instead of towards it. Default false. */54 invertTilt?: boolean;55 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */56 parallaxOffset?: number;57}5859/** 3. Text and 3D typography, for components that draw a label. */60interface Text3DProps {61 /** The label drawn by the component. */62 text?: string;63 /** Scale of the lettering. Default 1. */64 fontSize?: number;65 /** Extrusion depth of 3D letters. Default 0.2. */66 textDepth?: number;67 /** Bevelled, light-catching edges on 3D letters. Default true. */68 bevelEnabled?: boolean;69 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */70 fontUrl?: string;71}7273/** 4. Rendering, materials and glow. */74interface MaterialProps {75 /** Main color of the object. Default "#6366f1". */76 primaryColor?: string;77 /** Color of the glow. Default "#00f0ff". */78 emissiveColor?: string;79 /** Strength of the glow, 0 (none) to 3. Default 1. */80 emissiveIntensity?: number;81 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */82 roughness?: number;83 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */84 metalness?: number;85 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */86 transmission?: number;87 /** Technical wireframe rendering. Default false. */88 wireframe?: boolean;89}9091/** 5. Particles, idle motion and shader animation. */92interface MotionProps {93 /** Number of instanced elements. Default depends on the component. */94 particleCount?: number;95 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */96 autoRotateSpeed?: number;97 /** Pulses or ripples per second. Default 1. */98 pulseRate?: number;99 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */100 displacementScale?: number;101}102103/** 6. Environment and camera. */104interface EnvironmentProps {105 /** Camera field of view, in degrees. Default depends on the component. */106 cameraFov?: number;107 /** Color of the depth fog. Default "#0a0a0a". */108 fogColor?: string;109 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */110 fogDensity?: number;111}112113/** 7. Performance and accessibility. */114interface PerformanceProps {115 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */116 lowPowerMode?: boolean;117 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */118 respectReducedMotion?: boolean;119 /** Stop the render loop while the component is scrolled out of view. Default true. */120 pauseWhenOffscreen?: boolean;121}122123/** Every group at once. Components extend only the groups they apply (see the top of this file). */124interface Base3DComponentProps125 extends CursorProps,126 TiltProps,127 Text3DProps,128 MaterialProps,129 MotionProps,130 EnvironmentProps,131 PerformanceProps {}132133type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;134135/** The values a prop takes when it is left out. A component may override one, and then documents it. */136const DEFAULT_3D_PROPS: Defaults = {137 cursorRadius: 220,138 cursorForce: 1,139 magneticStrength: 0,140 cursorDamping: 0.1,141 maxTiltAngle: 15,142 tiltAxis: "both",143 invertTilt: false,144 parallaxOffset: 1,145 fontSize: 1,146 textDepth: 0.2,147 bevelEnabled: true,148 primaryColor: "#6366f1",149 emissiveColor: "#00f0ff",150 emissiveIntensity: 1,151 roughness: 0.3,152 metalness: 0.5,153 transmission: 0,154 wireframe: false,155 autoRotateSpeed: 0,156 pulseRate: 1,157 displacementScale: 1,158 fogColor: "#0a0a0a",159 fogDensity: 0,160 lowPowerMode: false,161 respectReducedMotion: true,162 pauseWhenOffscreen: true,163};164165/** Inline widget: fills its positioned parent and receives pointer events. */166const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };167168/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */169const OVERLAY_STYLE: CSSProperties = {170 position: "fixed",171 top: 0,172 left: 0,173 width: "100%",174 height: "100%",175 pointerEvents: "none",176 zIndex: 9999,177};178179/** Visually hidden but reachable by keyboard and screen readers. */180const SR_ONLY: CSSProperties = {181 position: "absolute",182 width: 1,183 height: 1,184 padding: 0,185 margin: -1,186 overflow: "hidden",187 clip: "rect(0, 0, 0, 0)",188 whiteSpace: "nowrap",189 border: 0,190};191192interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {193 children: ReactNode;194 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */195 overlay?: boolean;196}197198/**199 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel200 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.201 */202function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {203 const containerRef = useRef<HTMLDivElement>(null);204 // In view at first: the first frame is always drawn before the loop can be paused205 const [inView, setInView] = useState(true);206 useEffect(() => {207 const el = containerRef.current;208 if (!el || !pauseWhenOffscreen) return undefined;209 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));210 observer.observe(el);211 return () => observer.disconnect();212 }, [pauseWhenOffscreen]);213 return (214 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">215 <Canvas216 dpr={lowPowerMode ? 1 : dpr}217 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}218 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}219 style={overlay ? { pointerEvents: "none" } : undefined}220 {...canvasProps}221 >222 {children}223 </Canvas>224 </div>225 );226}227228export interface CityDatum {229 /** Column on the grid. */230 x: number;231 /** Row on the grid. */232 z: number;233 value: number;234 label: string;235}236237export interface CityGridProps extends Pick<MaterialProps, "primaryColor" | "emissiveColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {238 data: CityDatum[];239 primaryColor?: string;240 /** @deprecated Use `primaryColor`. */241 baseColor?: string;242 /** Color of the hovered building and of the tallest ones. */243 emissiveColor?: string;244 /** @deprecated Use `emissiveColor`. */245 highlightColor?: string;246 /** Height of the tallest building, in grid cells. Default 4. */247 maxHeight?: number;248 /** Formats the value shown in the tooltip. */249 formatValue?: (value: number) => string;250}251252const CELL = 1;253const FOOTPRINT = 0.78;254255const City = memo(function City({ data, primaryColor, baseColor = primaryColor ?? "#27272a", emissiveColor, highlightColor = emissiveColor ?? "#a78bfa", maxHeight = 4, formatValue = (v) => v.toLocaleString() }: CityGridProps) {256 const meshRef = useRef<THREE.InstancedMesh>(null);257 const gl = useThree((state) => state.gl);258 const camera = useThree((state) => state.camera) as THREE.OrthographicCamera;259 const size = useThree((state) => state.size);260 const [hovered, setHovered] = useState(-1);261 const grow = useRef({ started: false, progress: 0 });262 const count = data.length;263264 // Grid extents, to center the city and frame it265 const layout = useMemo(() => {266 const xs = data.map((d) => d.x);267 const zs = data.map((d) => d.z);268 const minX = Math.min(...xs);269 const maxX = Math.max(...xs);270 const minZ = Math.min(...zs);271 const maxZ = Math.max(...zs);272 const maxValue = Math.max(1e-6, ...data.map((d) => d.value));273 return { cx: (minX + maxX) / 2, cz: (minZ + maxZ) / 2, span: Math.max(maxX - minX, maxZ - minZ) + 1, maxValue };274 }, [data]);275276 const heights = useMemo(() => data.map((d) => Math.max(0.06, (d.value / layout.maxValue) * maxHeight)), [data, layout.maxValue, maxHeight]);277 const current = useMemo(() => new Float32Array(count), [count]);278 const highlight = useMemo(() => new Float32Array(count), [count]);279280 const geometry = useMemo(() => {281 const g = new RoundedBoxGeometry(FOOTPRINT, 1, FOOTPRINT, 2, 0.05);282 g.translate(0, 0.5, 0); // origin at the base: scaling Y raises the building283 return g;284 }, []);285 const material = useMemo(() => {286 const m = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.4, metalness: 0.25 });287 // Instance colors above 1 become emissive: the hovered building lights up from inside288 m.onBeforeCompile = (shader) => {289 shader.fragmentShader = shader.fragmentShader.replace(290 "#include <emissivemap_fragment>",291 "#include <emissivemap_fragment>\n#ifdef USE_COLOR\n totalEmissiveRadiance += max(vColor.rgb - 1.0, 0.0) * 1.2;\n#endif"292 );293 };294 return m;295 }, []);296 const ground = useMemo(() => new RoundedBoxGeometry(1, 0.2, 1, 2, 0.08), []);297 const groundMaterial = useMemo(() => new THREE.MeshStandardMaterial({ color: "#0d0d11", roughness: 0.8 }), []);298 const scratch = useMemo(299 () => ({ matrix: new THREE.Matrix4(), position: new THREE.Vector3(), quaternion: new THREE.Quaternion(), scale: new THREE.Vector3(), color: new THREE.Color(), base: new THREE.Color(), high: new THREE.Color() }),300 []301 );302303 useEffect(() => {304 scratch.base.set(baseColor);305 scratch.high.set(highlightColor);306 }, [scratch, baseColor, highlightColor]);307 useLayoutEffect(() => {308 const mesh = meshRef.current;309 if (!mesh) return;310 for (let i = 0; i < count; i++) mesh.setColorAt(i, scratch.base);311 mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);312 }, [count, scratch]);313 useEffect(() => () => geometry.dispose(), [geometry]);314 useEffect(() => () => material.dispose(), [material]);315 useEffect(316 () => () => {317 ground.dispose();318 groundMaterial.dispose();319 },320 [ground, groundMaterial]321 );322 useEffect(() => {323 const mesh = meshRef.current;324 return () => mesh?.dispose();325 }, [count]);326327 // Isometric framing: the orthographic zoom fits the city to the canvas328 useEffect(() => {329 const extent = layout.span * CELL * 1.5 + maxHeight * 0.8;330 camera.zoom = Math.min(size.width, size.height * 1.3) / extent;331 camera.updateProjectionMatrix();332 }, [camera, size, layout.span, maxHeight]);333334 // Buildings rise when the city scrolls into view335 useEffect(() => {336 const observer = new IntersectionObserver(([entry]) => {337 if (entry.isIntersecting) grow.current.started = true;338 });339 observer.observe(gl.domElement);340 return () => observer.disconnect();341 }, [gl]);342343 useFrame((_, delta) => {344 const mesh = meshRef.current;345 if (!mesh) return;346 const dt = Math.min(delta, 1 / 30);347 const g = grow.current;348 if (g.started) g.progress = Math.min(1, g.progress + dt * 0.8);349350 for (let i = 0; i < count; i++) {351 const d = data[i];352 // Staggered rise: buildings closer to the front start first353 const delay = ((d.x - layout.cx + d.z - layout.cz) / (layout.span * 2) + 0.5) * 0.45;354 const local = THREE.MathUtils.clamp((g.progress - delay) / 0.55, 0, 1);355 const eased = 1 - Math.pow(1 - local, 3);356 current[i] += (heights[i] * eased - current[i]) * (1 - Math.exp(-10 * dt));357 highlight[i] = THREE.MathUtils.damp(highlight[i], i === hovered ? 1 : 0, 12, dt);358359 scratch.position.set((d.x - layout.cx) * CELL, 0, (d.z - layout.cz) * CELL);360 scratch.scale.set(1, Math.max(0.001, current[i]), 1);361 mesh.setMatrixAt(i, scratch.matrix.compose(scratch.position, scratch.quaternion, scratch.scale));362 // Taller = closer to the highlight color; hovered = lit (HDR)363 const share = heights[i] / maxHeight;364 scratch.color.copy(scratch.base).lerp(scratch.high, share * share * 0.55).lerp(scratch.high, highlight[i]).multiplyScalar(1 + highlight[i] * 1.2);365 mesh.setColorAt(i, scratch.color);366 }367 mesh.instanceMatrix.needsUpdate = true;368 if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;369 });370371 const tip = hovered >= 0 ? data[hovered] : null;372373 return (374 <group>375 <mesh geometry={ground} material={groundMaterial} position={[0, -0.1, 0]} scale={[layout.span + 0.6, 1, layout.span + 0.6]} />376 <instancedMesh377 key={count}378 ref={meshRef}379 args={[geometry, material, count]}380 onPointerMove={(e: ThreeEvent<PointerEvent>) => {381 e.stopPropagation();382 if (e.instanceId !== undefined && e.instanceId !== hovered) setHovered(e.instanceId);383 gl.domElement.style.cursor = "pointer";384 }}385 onPointerOut={() => {386 setHovered(-1);387 gl.domElement.style.cursor = "";388 }}389 />390 {tip ? (391 <Html position={[(tip.x - layout.cx) * CELL, heights[hovered] + 0.35, (tip.z - layout.cz) * CELL]} center zIndexRange={[20, 0]} style={{ pointerEvents: "none" }}>392 <div393 style={{394 transform: "translateY(-50%)",395 whiteSpace: "nowrap",396 borderRadius: 12,397 background: "rgba(10,10,14,0.9)",398 border: "1px solid rgba(255,255,255,0.14)",399 padding: "8px 12px",400 color: "white",401 font: "500 12px/1.35 system-ui, sans-serif",402 boxShadow: "0 12px 30px rgba(0,0,0,0.5)",403 }}404 >405 <div style={{ opacity: 0.6 }}>{tip.label}</div>406 <div style={{ fontSize: 16, fontWeight: 700 }}>{formatValue(tip.value)}</div>407 </div>408 </Html>409 ) : null}410 </group>411 );412});413414/** Self-contained chart: fills its positioned parent, isometric view. */415function IsometricCityGrid3D(props: CityGridProps) {416 return (417 <>418 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode} orthographic camera={{ position: [10, 9, 10], zoom: 40, near: -100, far: 200 }} onCreated={({ camera }) => camera.lookAt(0, 0.6, 0)}>419 <ambientLight intensity={0.5} />420 <directionalLight position={[6, 10, 4]} intensity={2} />421 <directionalLight position={[-6, 4, -2]} intensity={0.6} color="#c4b5fd" />422 <Environment resolution={64} frames={1}>423 <Lightformer form="rect" intensity={2} position={[0, 6, 0]} rotation-x={Math.PI / 2} scale={[10, 10, 1]} />424 </Environment>425 <City {...props} />426 </UICanvas>427 <table style={SR_ONLY}>428 <tbody>429 {props.data.map((d, i) => (430 <tr key={i}>431 <th>{d.label}</th>432 <td>{(props.formatValue ?? ((v: number) => v.toLocaleString()))(d.value)}</td>433 </tr>434 ))}435 </tbody>436 </table>437 </>438 );439}440441export default memo(IsometricCityGrid3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import IsometricCityGrid3D from "@/components/IsometricCityGrid3D";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 <IsometricCityGrid3D8 maxHeight={4}9 primaryColor="#27272a"10 emissiveColor="#a78bfa"11 />12 </div>13 );14}