Globe
An interactive 3D globe for React built on WebGL with cobe: pin markers by latitude and longitude, draw arcs between cities, and let visitors drag it around with spring momentum. Neutral land dots with mint markers by default, sharp on high-DPI screens, responsive, and paused whenever it's off-screen.
- WebGL
- Markers & arcs
- Drag with momentum
- Keyboard rotation
- Pauses off-screen
- Reduced-motion safe
Every deploy reaches nine regions
Drag the globe to spin it, or focus it and use the arrow keys.
- San Francisco
- New York
- São Paulo
- London
- Frankfurt
- Mumbai
- Singapore
- Tokyo
- Sydney
import { Globe, type GlobeMarker } from "@/components/dusk/globe/globe";
const regions: GlobeMarker[] = [
{ location: [37.7749, -122.4194], size: 0.07, label: "San Francisco" },
{ location: [40.7128, -74.006], size: 0.08, label: "New York" },
{ location: [-23.5505, -46.6333], size: 0.06, label: "São Paulo" },
{ location: [51.5072, -0.1276], size: 0.07, label: "London" },
{ location: [50.1109, 8.6821], size: 0.05, label: "Frankfurt" },
{ location: [19.076, 72.8777], size: 0.07, label: "Mumbai" },
{ location: [1.3521, 103.8198], size: 0.06, label: "Singapore" },
{ location: [35.6762, 139.6503], size: 0.08, label: "Tokyo" },
{ location: [-33.8688, 151.2093], size: 0.05, label: "Sydney" },
];
export default function GlobeDemo() {
return (
<div className="relative flex w-full flex-col items-center overflow-hidden rounded-xl border border-white/10 bg-background px-6 pt-10">
<h3 className="text-center text-2xl font-semibold tracking-tight text-foreground sm:text-3xl">
Every deploy reaches nine regions
</h3>
<p className="mt-2 max-w-sm text-center text-sm text-white/60">Drag the globe to spin it, or focus it and use the arrow keys.</p>
<div className="relative -mb-40 mt-8 w-full max-w-[460px]">
<Globe markers={regions} label="Globe showing nine edge regions" />
</div>
<div aria-hidden className="pointer-events-none absolute inset-x-0 bottom-0 h-24 bg-gradient-to-t from-background to-transparent" />
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/globe.json1. Install the dependencies.
npm install cobe motion2. Copy the source into
components/dusk/globe/globe.tsx.globe.tsx "use client"; import * as React from "react"; import createGlobe, { type Arc, type COBEOptions, type Globe as CobeGlobe, type Marker } from "cobe"; import { useMotionValue, useReducedMotion, useSpring } from "motion/react"; import { cn } from "@/lib/utils"; export type GlobeMarker = { /** `[latitude, longitude]` in degrees. */ location: [number, number]; /** Dot size, roughly 0.02–0.1. Defaults to `0.05`. */ size?: number; /** Any CSS color. Defaults to `markerColor`. */ color?: string; /** Name of the place. Labelled markers are listed for screen readers. */ label?: string; }; export type GlobeArc = { /** `[latitude, longitude]` where the arc starts. */ from: [number, number]; /** `[latitude, longitude]` where the arc ends. */ to: [number, number]; /** Any CSS color. Defaults to `arcColor`. */ color?: string; }; export interface GlobeProps extends Omit<React.ComponentProps<"div">, "children"> { /** Points pinned to the globe. */ markers?: GlobeMarker[]; /** Curved lines between two locations. */ arcs?: GlobeArc[]; /** Spin on its own. Always off under reduced motion. */ autoRotate?: boolean; /** Auto-rotation speed in radians per second. */ speed?: number; /** Let people rotate the globe by dragging (and with the arrow keys). */ draggable?: boolean; /** Starting longitude rotation in radians. */ phi?: number; /** Tilt toward the viewer in radians. */ theta?: number; /** Color of the land dots. Any CSS color. */ baseColor?: string; /** Default marker color. Any CSS color. */ markerColor?: string; /** Color of the soft light around the rim. Keep it close to the background. Any CSS color. */ glowColor?: string; /** Default arc color. Any CSS color. */ arcColor?: string; /** `1` renders a dark globe, `0` a light one. */ dark?: number; /** Strength of the lighting falloff toward the edges. */ diffuse?: number; /** Brightness of the land dots. */ mapBrightness?: number; /** Number of dots used to draw the map. More is finer and heavier. */ mapSamples?: number; /** Accessible name of the globe. */ label?: string; /** Shown instead of the globe when WebGL isn't available. */ fallback?: React.ReactNode; } type RGB = [number, number, number]; /** Resolves any CSS color (theme variables, oklch…) to a 0–1 RGB triplet by painting one pixel. */ function resolveColor(host: HTMLElement, color: string): RGB { const probe = document.createElement("span"); probe.style.color = color; probe.style.display = "none"; host.appendChild(probe); const computed = getComputedStyle(probe).color; probe.remove(); const ctx = document.createElement("canvas").getContext("2d", { willReadFrequently: true }); if (!ctx) return [1, 1, 1]; ctx.fillStyle = computed; ctx.fillRect(0, 0, 1, 1); const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data; return [r / 255, g / 255, b / 255]; } let webglSupport: boolean | undefined; function detectWebGL() { if (webglSupport === undefined) { try { const canvas = document.createElement("canvas"); const gl = canvas.getContext("webgl2") ?? canvas.getContext("webgl"); webglSupport = !!gl; gl?.getExtension("WEBGL_lose_context")?.loseContext(); } catch { webglSupport = false; } } return webglSupport; } const noopSubscribe = () => () => {}; const THETA_MIN = -0.6; const THETA_MAX = 0.9; /** Interactive WebGL globe with markers and arcs that auto-rotates and spins with spring momentum when dragged. */ export function Globe({ markers = [], arcs = [], autoRotate = true, speed = 0.2, draggable = true, phi = 0, theta = 0.25, baseColor = "oklch(0.4 0 0)", markerColor = "var(--color-primary)", glowColor = "oklch(0.18 0 0)", arcColor = "oklch(0.7 0 0)", dark = 1, diffuse = 1.2, mapBrightness = 4, mapSamples = 16000, label = "Interactive globe", fallback, className, style, onPointerDown, onKeyDown, ...props }: GlobeProps) { const reduceMotion = useReducedMotion() ?? false; // The server and the first client render assume WebGL; the client corrects it right after hydration. const supported = React.useSyncExternalStore(noopSubscribe, detectWebGL, () => true); const rootRef = React.useRef<HTMLDivElement>(null); const hostRef = React.useRef<HTMLDivElement>(null); const globeRef = React.useRef<CobeGlobe | null>(null); const requestFrameRef = React.useRef<() => void>(() => {}); const applyMarkersRef = React.useRef<() => void>(() => {}); const live = React.useRef({ autoRotate, speed, reduceMotion }); const dragging = React.useRef(false); // Drag offsets. The springs trail the raw values, which gives the release its momentum. const dragPhi = useMotionValue(0); const dragTheta = useMotionValue(0); const springPhi = useSpring(dragPhi, { stiffness: 60, damping: 18, mass: 1 }); const springTheta = useSpring(dragTheta, { stiffness: 60, damping: 18, mass: 1 }); React.useEffect(() => { live.current = { autoRotate, speed, reduceMotion }; requestFrameRef.current(); }, [autoRotate, speed, reduceMotion]); // Create the WebGL globe. The canvas is made here, outside React, because cobe re-parents it. React.useEffect(() => { const root = rootRef.current; const host = hostRef.current; if (!root || !host || !supported) return; const colors = { baseColor: resolveColor(root, baseColor), markerColor: resolveColor(root, markerColor), glowColor: resolveColor(root, glowColor), arcColor: resolveColor(root, arcColor), }; let canvas: HTMLCanvasElement | null = null; let globe: CobeGlobe | null = null; let size = Math.max(1, root.clientWidth); let basePhi = phi; let raf = 0; let last = 0; let onScreen = false; let shown = false; let textureTimers: ReturnType<typeof setTimeout>[] = []; const currentPhi = () => basePhi + (live.current.reduceMotion ? dragPhi.get() : springPhi.get()); const currentTheta = () => { const t = theta + (live.current.reduceMotion ? dragTheta.get() : springTheta.get()); return Math.min(THETA_MAX, Math.max(THETA_MIN, t)); }; // Auto-rotation holds still while the globe is being dragged. const spinning = () => live.current.autoRotate && !live.current.reduceMotion && !dragging.current; const frame = (now: number) => { raf = 0; if (!globe) return; const dt = last ? Math.min((now - last) / 1000, 0.1) : 0; last = now; if (spinning()) basePhi += live.current.speed * dt; globe.update({ phi: currentPhi(), theta: currentTheta() }); if (!shown && canvas) { shown = true; canvas.style.opacity = "1"; } if (spinning()) requestFrame(); else last = 0; }; const requestFrame = () => { if (raf || !globe || !onScreen || document.hidden) return; raf = requestAnimationFrame(frame); }; requestFrameRef.current = requestFrame; const build = () => { const dpr = Math.min(window.devicePixelRatio || 1, 2); canvas = document.createElement("canvas"); canvas.setAttribute("aria-hidden", "true"); canvas.style.cssText = "display:block;width:100%;height:100%;opacity:0;transition:opacity 700ms ease"; host.appendChild(canvas); const options: COBEOptions = { devicePixelRatio: dpr, width: size, height: size, phi: currentPhi(), theta: currentTheta(), dark, diffuse, mapSamples, mapBrightness, ...colors, markers: [], arcs: [], arcWidth: 0.6, arcHeight: 0.25, markerElevation: 0.01, }; globe = createGlobe(canvas, options); globeRef.current = globe; shown = false; // cobe decodes its map texture asynchronously; repaint once it has landed, even when nothing spins. textureTimers.forEach(clearTimeout); textureTimers = [150, 600].map((ms) => setTimeout(requestFrame, ms)); }; const teardown = () => { textureTimers.forEach(clearTimeout); textureTimers = []; cancelAnimationFrame(raf); raf = 0; globe?.destroy(); globe = null; globeRef.current = null; if (canvas) { const gl = canvas.getContext("webgl2") ?? canvas.getContext("webgl"); gl?.getExtension("WEBGL_lose_context")?.loseContext(); // cobe wraps the canvas in its own div; remove whichever is attached to the host. const wrapper = canvas.parentElement === host ? canvas : canvas.parentElement; wrapper?.remove(); canvas = null; } }; build(); applyMarkersRef.current(); const resizeObserver = new ResizeObserver(() => { const next = Math.max(1, root.clientWidth); if (next === size) return; size = next; globe?.update({ width: size, height: size, phi: currentPhi(), theta: currentTheta() }); }); resizeObserver.observe(root); const intersectionObserver = new IntersectionObserver(([entry]) => { onScreen = entry.isIntersecting; if (onScreen) requestFrame(); else { cancelAnimationFrame(raf); raf = 0; last = 0; } }); intersectionObserver.observe(root); const onVisibility = () => { if (document.hidden) { cancelAnimationFrame(raf); raf = 0; last = 0; } else requestFrame(); }; document.addEventListener("visibilitychange", onVisibility); // Rebuild at the new pixel ratio when the window moves to another screen or the page zooms. let dprQuery: MediaQueryList | null = null; const onDprChange = () => { teardown(); build(); applyMarkersRef.current(); watchDpr(); requestFrame(); }; const watchDpr = () => { dprQuery?.removeEventListener("change", onDprChange); dprQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); dprQuery.addEventListener("change", onDprChange); }; watchDpr(); // Every drag change (and every spring step after release) asks for a frame. const unsubscribers = [springPhi, springTheta, dragPhi, dragTheta].map((v) => v.on("change", requestFrame)); return () => { unsubscribers.forEach((off) => off()); resizeObserver.disconnect(); intersectionObserver.disconnect(); document.removeEventListener("visibilitychange", onVisibility); dprQuery?.removeEventListener("change", onDprChange); requestFrameRef.current = () => {}; teardown(); }; }, [ supported, baseColor, markerColor, glowColor, arcColor, dark, diffuse, mapSamples, mapBrightness, phi, theta, dragPhi, dragTheta, springPhi, springTheta, ]); // Markers and arcs update in place, so inline arrays never rebuild the WebGL context. const markersKey = JSON.stringify(markers.map(({ location, size, color }) => [location, size, color])); const arcsKey = JSON.stringify(arcs.map(({ from, to, color }) => [from, to, color])); React.useEffect(() => { const root = rootRef.current; if (!root) return; const apply = () => { const globe = globeRef.current; if (!globe) return; const parsedMarkers = JSON.parse(markersKey) as [[number, number], number | undefined, string | undefined][]; const parsedArcs = JSON.parse(arcsKey) as [[number, number], [number, number], string | undefined][]; const nextMarkers: Marker[] = parsedMarkers.map(([location, size, color]) => ({ location, size: size ?? 0.05, ...(color ? { color: resolveColor(root, color) } : null), })); const nextArcs: Arc[] = parsedArcs.map(([from, to, color]) => ({ from, to, ...(color ? { color: resolveColor(root, color) } : null), })); globe.update({ markers: nextMarkers, arcs: nextArcs }); requestFrameRef.current(); }; // The globe is rebuilt when colors or the pixel ratio change; it re-applies markers through this ref. applyMarkersRef.current = apply; apply(); }, [markersKey, arcsKey]); const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => { onPointerDown?.(event); if (!draggable || event.defaultPrevented || (event.pointerType === "mouse" && event.button !== 0)) return; const el = event.currentTarget; const width = Math.max(1, el.clientWidth); const startX = event.clientX; const startY = event.clientY; const startPhi = dragPhi.get(); const startTheta = dragTheta.get(); el.setPointerCapture(event.pointerId); dragging.current = true; const move = (e: PointerEvent) => { // Dragging across the full width turns the globe half way round. dragPhi.set(startPhi + ((e.clientX - startX) / width) * Math.PI); const t = startTheta + ((e.clientY - startY) / width) * Math.PI * 0.5; dragTheta.set(Math.min(THETA_MAX - theta, Math.max(THETA_MIN - theta, t))); }; const end = () => { el.removeEventListener("pointermove", move); el.removeEventListener("pointerup", end); el.removeEventListener("pointercancel", end); dragging.current = false; requestFrameRef.current(); if (reduceMotion) return; // Fling: push the target along the release velocity so the spring glides on. const velocity = dragPhi.getVelocity(); if (Number.isFinite(velocity)) dragPhi.set(dragPhi.get() + Math.max(-4, Math.min(4, velocity * 0.18))); }; el.addEventListener("pointermove", move); el.addEventListener("pointerup", end); el.addEventListener("pointercancel", end); }; const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { onKeyDown?.(event); if (!draggable || event.defaultPrevented) return; const step = event.shiftKey ? 0.6 : 0.25; if (event.key === "ArrowLeft") dragPhi.set(dragPhi.get() - step); else if (event.key === "ArrowRight") dragPhi.set(dragPhi.get() + step); else if (event.key === "ArrowUp") dragTheta.set(Math.max(THETA_MIN - theta, dragTheta.get() - step * 0.5)); else if (event.key === "ArrowDown") dragTheta.set(Math.min(THETA_MAX - theta, dragTheta.get() + step * 0.5)); else return; event.preventDefault(); }; const named = markers.filter((m) => m.label); return ( <div ref={rootRef} data-slot="globe" role={named.length > 0 ? "group" : "img"} aria-label={label} aria-roledescription={draggable ? "interactive globe" : "globe"} aria-keyshortcuts={draggable ? "ArrowLeft ArrowRight ArrowUp ArrowDown" : undefined} tabIndex={draggable ? 0 : undefined} className={cn( "relative aspect-square w-full max-w-[600px] select-none rounded-full outline-none", "focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-background", draggable && supported && "cursor-grab touch-pan-y active:cursor-grabbing", className )} style={style} onPointerDown={handlePointerDown} onKeyDown={handleKeyDown} {...props} > <div ref={hostRef} className="absolute inset-0" /> {!supported && (fallback ?? ( <div aria-hidden className="absolute inset-[6%] rounded-full border bg-card" /> ))} {named.length > 0 && ( <ul className="sr-only" aria-label="Marked locations"> {named.map((m, i) => ( <li key={`${m.label}-${i}`}>{m.label}</li> ))} </ul> )} </div> ); }
The globe is square and fills the width of its parent up to max-w-[600px]; override it with className. Colors accept any CSS color, including theme variables like var(--color-primary).
Usage
import { Globe } from "@/components/dusk/globe/globe"
export function Network() {
return (
<Globe
className="max-w-md"
markers={[
{ location: [37.77, -122.42], label: "San Francisco" },
{ location: [51.51, -0.13], label: "London" },
{ location: [35.68, 139.65], size: 0.08, label: "Tokyo" },
]}
/>
)
}Examples
Arcs
Pass arcs with from and to coordinates to draw routes. Each marker and arc can set its own color; phi and theta set the starting rotation and tilt.
Arcs
Connect locations with curved arcs. The hub marker overrides the default color with its own.
- Berlin (hub)
import { Globe, type GlobeArc, type GlobeMarker } from "@/components/dusk/globe/globe";
const hub: [number, number] = [52.52, 13.405];
const spokes: [number, number][] = [
[40.7128, -74.006],
[-1.2921, 36.8219],
[25.2048, 55.2708],
[35.6762, 139.6503],
[-33.9249, 18.4241],
];
const markers: GlobeMarker[] = [
{ location: hub, size: 0.08, color: "#ffffff", label: "Berlin (hub)" },
...spokes.map((location) => ({ location, size: 0.05 })),
];
const arcs: GlobeArc[] = spokes.map((to) => ({ from: hub, to }));
export default function GlobeArcs() {
return (
<div className="flex w-full flex-col items-center gap-6 rounded-xl border border-white/10 bg-background p-6 sm:flex-row sm:justify-between sm:p-10">
<div className="max-w-xs">
<p className="text-sm font-medium text-white">Arcs</p>
<p className="mt-1 text-sm text-white/60">
Connect locations with curved arcs. The hub marker overrides the default color with its own.
</p>
</div>
<Globe
className="max-w-[320px]"
markers={markers}
arcs={arcs}
phi={-0.4}
theta={0.35}
speed={0.12}
label="Globe with routes from Berlin"
/>
</div>
);
}Colors and static globes
Retint with baseColor, glowColor and markerColor. Set autoRotate and draggable to false for a still globe; the render loop then stops entirely after the first frame.
import { Globe } from "@/components/dusk/globe/globe";
export default function GlobeColors() {
return (
<div className="grid w-full gap-6 rounded-xl border border-white/10 bg-background p-6 sm:grid-cols-2">
<figure className="flex flex-col items-center gap-3">
<Globe
className="max-w-[240px]"
baseColor="#4b5568"
glowColor="#11151c"
markerColor="#93c5fd"
markers={[{ location: [64.1466, -21.9426], size: 0.08 }]}
mapBrightness={5}
label="Blue globe"
/>
<figcaption className="text-sm text-white/60">Custom colors</figcaption>
</figure>
<figure className="flex flex-col items-center gap-3">
<Globe
className="max-w-[240px]"
autoRotate={false}
draggable={false}
phi={4.6}
theta={0.2}
baseColor="#5c544b"
glowColor="#1a1714"
markerColor="#fdba74"
mapSamples={9000}
markers={[{ location: [-1.2921, 36.8219], size: 0.08 }]}
label="Static warm-gray globe centred on Africa"
/>
<figcaption className="text-sm text-white/60">Static: no rotation or dragging</figcaption>
</figure>
</div>
);
}API Reference
Any other div prop is passed to the root. Markers and arcs update in place without rebuilding the WebGL context; changing a color, phi, theta or the map settings rebuilds it.
| Prop | Type | Default | Description |
|---|---|---|---|
| markers | GlobeMarker[] | [] | Points to pin: { location: [lat, lng], size?, color?, label? }. |
| arcs | GlobeArc[] | [] | Curved routes: { from: [lat, lng], to: [lat, lng], color? }. |
| autoRotate | boolean | true | Spin on its own. Always off under reduced motion. |
| speed | number | 0.2 | Auto-rotation speed in radians per second. |
| draggable | boolean | true | Rotate by dragging (with momentum) and with the arrow keys. |
| phi | number | 0 | Starting longitude rotation in radians. |
| theta | number | 0.25 | Tilt toward the viewer in radians. |
| baseColor | string | "oklch(0.4 0 0)" | Color of the land dots. |
| markerColor | string | "var(--color-primary)" | Default marker color. |
| glowColor | string | "oklch(0.18 0 0)" | Soft rim light. Keep it close to the background. |
| arcColor | string | "oklch(0.7 0 0)" | Default arc color. |
| dark | number | 1 | 1 for a dark globe, 0 for a light one. |
| diffuse | number | 1.2 | Lighting falloff toward the edges. |
| mapBrightness | number | 6 | Brightness of the land dots. |
| mapSamples | number | 16000 | Number of dots drawn for the map. Lower is lighter. |
| label | string | "Interactive globe" | Accessible name. |
| fallback | ReactNode | — | Shown instead of the globe when WebGL is unavailable. Defaults to a soft CSS sphere. |
Accessibility
- The globe has an accessible name (
label), and markers with alabelare listed for screen readers. - When draggable it is focusable: the arrow keys rotate and tilt it (hold Shift for bigger steps).
- With prefers-reduced-motion it never auto-rotates and drags move it directly, without momentum.
- Rendering stops while the globe is off-screen or the tab is hidden, and the WebGL context is released on unmount.
- Without WebGL a static fallback keeps the layout intact.