← All components Next componentScroll Compass→
Extras · Tags
Word Cloud Globe
A globe of words that always face you: the pointer steers it, hovering a word picks it out.
<WordCloudGlobe3D />Live
Move the pointer to steer it
Customize
Words#e4e4e7
Hovered#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 word-cloud-globe
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/WordCloudGlobe3D.tsx and paste it in.
components/WordCloudGlobe3D.tsx
1"use client";23import {4 memo,5 useEffect,6 useLayoutEffect,7 useMemo,8 useRef,9 useState,10 type CSSProperties,11 type ReactNode,12 type RefObject,13} from "react";14import * as THREE from "three";15import { Canvas, useFrame, useThree, type CanvasProps, type ThreeEvent } from "@react-three/fiber";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/** Inline widget: fills its positioned parent and receives pointer events. */165const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };166167/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */168const OVERLAY_STYLE: CSSProperties = {169 position: "fixed",170 top: 0,171 left: 0,172 width: "100%",173 height: "100%",174 pointerEvents: "none",175 zIndex: 9999,176};177178/** Visually hidden but reachable by keyboard and screen readers. */179const SR_ONLY: CSSProperties = {180 position: "absolute",181 width: 1,182 height: 1,183 padding: 0,184 margin: -1,185 overflow: "hidden",186 clip: "rect(0, 0, 0, 0)",187 whiteSpace: "nowrap",188 border: 0,189};190191interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {192 children: ReactNode;193 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */194 overlay?: boolean;195}196197/**198 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel199 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.200 */201function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {202 const containerRef = useRef<HTMLDivElement>(null);203 // In view at first: the first frame is always drawn before the loop can be paused204 const [inView, setInView] = useState(true);205 useEffect(() => {206 const el = containerRef.current;207 if (!el || !pauseWhenOffscreen) return undefined;208 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));209 observer.observe(el);210 return () => observer.disconnect();211 }, [pauseWhenOffscreen]);212 return (213 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">214 <Canvas215 dpr={lowPowerMode ? 1 : dpr}216 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}217 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}218 style={overlay ? { pointerEvents: "none" } : undefined}219 {...canvasProps}220 >221 {children}222 </Canvas>223 </div>224 );225}226227/**228 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid229 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).230 */231function PixelPerspective({ fov = 30 }: { fov?: number }) {232 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;233 const size = useThree((state) => state.size);234 useLayoutEffect(() => {235 camera.fov = fov;236 camera.near = 1;237 camera.far = 20000;238 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));239 camera.lookAt(0, 0, 0);240 camera.updateProjectionMatrix();241 }, [camera, size, fov]);242 return null;243}244245function pageFontFamily() {246 if (typeof document === "undefined") return "sans-serif";247 return getComputedStyle(document.body).fontFamily || "sans-serif";248}249250let measureContext: CanvasRenderingContext2D | null = null;251252/** Width of a label in CSS pixels, in the page's font. */253function measureLabel(text: string, fontSize: number, fontWeight = 600) {254 if (typeof document === "undefined") return text.length * fontSize * 0.6;255 measureContext ??= document.createElement("canvas").getContext("2d");256 if (!measureContext) return text.length * fontSize * 0.6;257 measureContext.font = `${fontWeight} ${fontSize}px ${pageFontFamily()}`;258 return measureContext.measureText(text).width;259}260261interface LabelOptions {262 text: string;263 /** Second, smaller line under the text. */264 subtext?: string;265 /** Glyph drawn before the text (emoji, arrow, symbol…). */266 icon?: string;267 width: number;268 height: number;269 color: string;270 /** Face color; transparent when omitted. */271 background?: string;272 fontSize?: number;273 fontWeight?: number;274 /** Wrap the text over several lines within the width (minus padding). */275 wrap?: boolean;276 align?: "center" | "left";277 /** Horizontal padding, in CSS pixels (used by wrapping and left alignment). Default 0. */278 padding?: number;279 /** Line height, as a multiple of the font size. Default 1.35. */280 lineHeight?: number;281}282283function wrapLines(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {284 const lines: string[] = [];285 let line = "";286 for (const word of text.split(/\s+/)) {287 const candidate = line ? `${line} ${word}` : word;288 if (line && ctx.measureText(candidate).width > maxWidth) {289 lines.push(line);290 line = word;291 } else {292 line = candidate;293 }294 }295 if (line) lines.push(line);296 return lines;297}298299function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {300 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane301 const scale = Math.min(Math.max(window.devicePixelRatio || 1, 2), 3);302 canvas.width = Math.max(2, Math.ceil(o.width * scale));303 canvas.height = Math.max(2, Math.ceil(o.height * scale));304 const ctx = canvas.getContext("2d");305 if (!ctx) return;306 ctx.setTransform(scale, 0, 0, scale, 0, 0);307 ctx.clearRect(0, 0, o.width, o.height);308 if (o.background) {309 ctx.fillStyle = o.background;310 ctx.fillRect(0, 0, o.width, o.height);311 }312313 const family = pageFontFamily();314 const size = o.fontSize ?? 15;315 const weight = o.fontWeight ?? 600;316 ctx.fillStyle = o.color;317 ctx.textBaseline = "middle";318 ctx.textAlign = "center";319320 const padding = o.padding ?? 0;321 const left = o.align === "left";322 ctx.textAlign = left ? "left" : "center";323 const x = left ? padding : o.width / 2;324325 let text = o.text;326 if (o.icon) text = `${o.icon} ${text}`;327 ctx.font = `${weight} ${size}px ${family}`;328329 if (o.wrap) {330 const step = size * (o.lineHeight ?? 1.35);331 const lines = wrapLines(ctx, text, o.width - padding * 2);332 // Only as many lines as fit; the last one kept ends with an ellipsis333 const maxLines = Math.max(1, Math.floor(o.height / step));334 if (lines.length > maxLines) {335 lines.length = maxLines;336 let last = lines[maxLines - 1];337 while (last && ctx.measureText(`${last}…`).width > o.width - padding * 2) last = last.slice(0, -1);338 lines[maxLines - 1] = `${last.trimEnd()}…`;339 }340 const top = o.height / 2 - ((lines.length - 1) * step) / 2;341 lines.forEach((line, i) => ctx.fillText(line, x, top + i * step));342 return;343 }344345 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;346 ctx.fillText(text, x, mainY);347348 if (o.subtext) {349 ctx.globalAlpha = 0.7;350 ctx.font = `500 ${Math.round(size * 0.72)}px ${family}`;351 ctx.fillText(o.subtext, x, o.height * 0.7);352 ctx.globalAlpha = 1;353 }354}355356/**357 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's358 * <Text>). Redrawn once web fonts finish loading; disposed on unmount.359 */360function useLabelTexture(options: LabelOptions) {361 const key = JSON.stringify(options);362 const [fontsVersion, setFontsVersion] = useState(0);363 useEffect(() => {364 let alive = true;365 document.fonts?.ready.then(() => {366 if (alive) setFontsVersion((v) => v + 1);367 });368 return () => {369 alive = false;370 };371 }, []);372373 const texture = useMemo(() => {374 const t = new THREE.CanvasTexture(document.createElement("canvas"));375 t.colorSpace = THREE.SRGBColorSpace;376 t.anisotropy = 4;377 return t;378 }, []);379380 useLayoutEffect(() => {381 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);382 texture.needsUpdate = true;383 }, [texture, key, fontsVersion]);384385 useEffect(() => () => texture.dispose(), [texture]);386 return texture;387}388389export interface WordCloudGlobeProps extends Pick<MaterialProps, "emissiveColor">, Pick<MotionProps, "autoRotateSpeed">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {390 words: string[];391 /** Radius of the globe, in CSS pixels. Default: fits the container. */392 radius?: number;393 textColor?: string;394 /** Color of the hovered word. */395 emissiveColor?: string;396 /** @deprecated Use `emissiveColor`. */397 activeColor?: string;398 /** Idle spin, in radians per second. Default 0.25. */399 autoRotateSpeed?: number;400}401402const FONT_SIZE = 22;403const LABEL_HEIGHT = 34;404const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));405406interface WordProps {407 word: string;408 index: number;409 position: THREE.Vector3;410 geometry: THREE.PlaneGeometry;411 hovered: RefObject<number>;412 colors: { text: THREE.Color; active: THREE.Color };413}414415/** One word: a label texture on a plane that always faces the camera (billboard). */416const Word = memo(function Word({ word, index, position, geometry, hovered, colors }: WordProps) {417 const meshRef = useRef<THREE.Mesh>(null);418 const gl = useThree((state) => state.gl);419 const width = Math.ceil(measureLabel(word, FONT_SIZE, 600)) + 16;420 const texture = useLabelTexture({ text: word, width, height: LABEL_HEIGHT, color: "#ffffff", fontSize: FONT_SIZE, fontWeight: 600 });421 const material = useMemo(() => new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }), []);422 const scratch = useMemo(() => ({ world: new THREE.Vector3(), parentQuat: new THREE.Quaternion(), hover: 0 }), []);423424 useEffect(() => {425 material.map = texture;426 material.needsUpdate = true;427 }, [material, texture]);428 useEffect(() => () => material.dispose(), [material]);429430 useFrame((state, delta) => {431 const mesh = meshRef.current;432 if (!mesh || !mesh.parent) return;433 // Billboard: undo the globe's rotation so the word faces the camera434 mesh.parent.getWorldQuaternion(scratch.parentQuat);435 mesh.quaternion.copy(scratch.parentQuat.invert()).multiply(state.camera.quaternion);436437 // Depth cue: words on the far side shrink and fade438 mesh.getWorldPosition(scratch.world);439 const radius = position.length() || 1;440 const front = THREE.MathUtils.clamp(scratch.world.z / radius, -1, 1) * 0.5 + 0.5;441 scratch.hover = THREE.MathUtils.damp(scratch.hover, hovered.current === index ? 1 : 0, 10, delta);442 const scale = 0.72 + front * 0.38 + scratch.hover * 0.35;443 mesh.scale.set(width * scale, LABEL_HEIGHT * scale, 1);444 material.opacity = 0.18 + front * 0.82;445 material.color.copy(colors.text).lerp(colors.active, scratch.hover);446 mesh.renderOrder = Math.round(front * 100);447 });448449 return (450 <mesh451 ref={meshRef}452 geometry={geometry}453 material={material}454 position={position}455 onPointerOver={(e: ThreeEvent<PointerEvent>) => {456 e.stopPropagation();457 hovered.current = index;458 gl.domElement.style.cursor = "pointer";459 }}460 onPointerOut={() => {461 if (hovered.current === index) hovered.current = -1;462 gl.domElement.style.cursor = "";463 }}464 />465 );466});467468const Globe = memo(function Globe({ words, radius, textColor = "#e4e4e7", emissiveColor, activeColor = emissiveColor ?? "#a78bfa", autoRotateSpeed = 0.25 }: WordCloudGlobeProps) {469 const groupRef = useRef<THREE.Group>(null);470 const gl = useThree((state) => state.gl);471 const size = useThree((state) => state.size);472 const hovered = useRef(-1);473 const pointer = useRef({ inside: false });474 const spin = useMemo(() => ({ velocity: new THREE.Vector2(0, autoRotateSpeed), target: new THREE.Vector2(), axis: new THREE.Vector3(), q: new THREE.Quaternion() }), [autoRotateSpeed]);475 const colors = useMemo(() => ({ text: new THREE.Color(), active: new THREE.Color() }), []);476 const geometry = useMemo(() => new THREE.PlaneGeometry(1, 1), []);477478 useEffect(() => {479 colors.text.set(textColor);480 colors.active.set(activeColor);481 }, [colors, textColor, activeColor]);482 useEffect(() => () => geometry.dispose(), [geometry]);483484 // Is the pointer over the canvas? (R3F's state.pointer keeps its last value after leaving)485 useEffect(() => {486 const el = gl.domElement;487 const enter = () => {488 pointer.current.inside = true;489 };490 const leave = () => {491 pointer.current.inside = false;492 };493 el.addEventListener("pointerenter", enter);494 el.addEventListener("pointerleave", leave);495 return () => {496 el.removeEventListener("pointerenter", enter);497 el.removeEventListener("pointerleave", leave);498 };499 }, [gl]);500501 const globeRadius = radius ?? Math.max(80, Math.min(size.width, size.height) * 0.36);502 const wordsKey = words.join("\n");503 const positions = useMemo(() => {504 const list = wordsKey ? wordsKey.split("\n") : [];505 return list.map((_, i) => {506 const y = 1 - ((i + 0.5) / list.length) * 2;507 const r = Math.sqrt(1 - y * y);508 const theta = i * GOLDEN_ANGLE;509 return new THREE.Vector3(Math.cos(theta) * r, y, Math.sin(theta) * r).multiplyScalar(globeRadius);510 });511 }, [wordsKey, globeRadius]);512513 useFrame((state, delta) => {514 const group = groupRef.current;515 if (!group) return;516 const dt = Math.min(delta, 1 / 30);517 // Spin direction follows the pointer (further from the center = faster); idle spin otherwise.518 // Hovering a word nearly stops the globe so it can be read.519 const p = state.pointer;520 const target = pointer.current.inside ? spin.target.set(-p.y * 1.4, p.x * 1.4) : spin.target.set(0, autoRotateSpeed);521 if (hovered.current !== -1) target.multiplyScalar(0.08);522 spin.velocity.lerp(target, 1 - Math.exp(-3 * dt));523524 const speed = spin.velocity.length();525 if (speed > 1e-5) {526 spin.axis.set(spin.velocity.x, spin.velocity.y, 0).normalize();527 spin.q.setFromAxisAngle(spin.axis, speed * dt);528 group.quaternion.premultiply(spin.q);529 }530 });531532 return (533 <group ref={groupRef}>534 {words.map((word, i) => (535 <Word key={`${i}-${word}`} word={word} index={i} position={positions[i]} geometry={geometry} hovered={hovered} colors={colors} />536 ))}537 </group>538 );539});540541/** Self-contained globe: fills its positioned parent. */542function WordCloudGlobe3D(props: WordCloudGlobeProps) {543 return (544 <>545 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode}>546 <PixelPerspective fov={35} />547 <Globe {...props} />548 </UICanvas>549 <ul style={SR_ONLY}>550 {props.words.map((word, i) => (551 <li key={`${i}-${word}`}>{word}</li>552 ))}553 </ul>554 </>555 );556}557558export default memo(WordCloudGlobe3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import WordCloudGlobe3D from "@/components/WordCloudGlobe3D";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 <WordCloudGlobe3D8 words={[9 "React",10 "Three.js",11 "WebGL",12 "GLSL",13 "Shaders",14 "Next.js",15 "R3F",16 "Drei",17 "GSAP",18 "Lenis",19 "Tailwind",20 "TypeScript",21 "Blender",22 "Motion",23 "Physics",24 "Chrome",25 "Design",26 "Bloom",27 ]}28 autoRotateSpeed={0.25}29 textColor="#e4e4e7"30 emissiveColor="#a78bfa"31 />32 </div>33 );34}