Pan and zoom
Zoomable diagrams, charts and maps inside a scrolling page — without trapping the scroll.
Architecture diagrams, charts, floor plans and maps are often wider than the text column. On a phone, the labels in a 1000 px diagram shrink to a few pixels, so readers need to zoom into it.
The simplest answer is no custom zoom at all: keep browser zoom enabled
(don't set user-scalable=no), or link the image so it opens at full size.
Custom pan and zoom earns its place when people explore the content in
place — following arrows in a diagram, comparing two areas of a chart.
The scroll trap
Most zoom widgets take over the gestures the page already uses to scroll: the mouse wheel zooms, and dragging with one finger pans. Scroll through the text on a desktop and the diagram starts zooming the moment the cursor passes over it. On a phone the diagram can fill most of the screen, and then there is no place left to put a finger that scrolls the page.
Try scrolling past this one with the mouse wheel, or with one finger on a phone:
Plus and minus keys zoom, arrow keys move the zoomed diagram, 0 resets.
Google Maps ran into this with maps embedded in articles, and in 2016
introduced
cooperative gesture handling:
one finger scrolls the page, and two fingers move the map. Mapbox GL JS and
MapLibre have the same idea as the cooperativeGestures option.
Cooperative gestures
The fix is to give the widget only the gestures the page doesn't use for scrolling:
| intention | mouse | trackpad | touchscreen |
|---|---|---|---|
| scroll | wheel | two-finger drag | one-finger drag |
| pan | drag | click and drag | two-finger drag |
| zoom | Ctrl / ⌘ + wheel | pinch | pinch |
| zoom in | double click, ⌘ + click | double click | double tap |
| zoom out | Alt + click | — | — |
| reset | double click when zoomed | same | double tap |
The page scrolls the same way it does everywhere else, and the diagram still has a full set of gestures. When someone does try a page gesture on it, a short hint says what to do instead: "Use two fingers to move and zoom" on touch, "Use ⌘ + scroll to zoom" with a mouse or trackpad.
Plus and minus keys zoom, arrow keys move the zoomed diagram, 0 resets.
This mapping comes from
@beoe/pan-zoom,
a small library for zoomable diagrams.
Details that matter
- Zoom around the pointer. Keep the point under the cursor, or between the two fingers, still while the scale changes. Zooming toward the centre makes people chase the part they wanted.
- A trackpad pinch arrives as Ctrl + wheel. Chrome, Firefox and macOS
Safari report a pinch as a
wheelevent withctrlKey: trueand the scale step indeltaY(WebKit bug 230545). One handler covers both pinch and Ctrl + mouse wheel. CallpreventDefault()only for these events, otherwise the browser zooms the whole page. - Use an exponential factor, and clamp the delta. Pinch events have
small deltas, but one mouse-wheel notch is often around 100 px. A linear
factor like
1 - deltaY * 0.01becomes zero or negative on one notch.Math.exp(-deltaY * 0.01)stays positive, and clampingdeltaYto ±50 keeps a wheel notch from jumping several steps at once. - Limit scale and position, but stretch at the limit. The demo zooms from 100% to 800%, and the edges of the diagram never stay inside the frame, so nobody can lose it off-screen. A hard stop makes a drag at 100% do nothing, which feels broken. Instead the diagram follows the pointer with growing resistance — the same rubber band iOS uses at the end of a scroll view — and springs back on release.
- Tell the browser up front with
touch-action.pan-x pan-ylets one finger scroll the page natively, and turns off the browser's pinch zoom and double-tap zoom inside the frame. The two-finger pan still needspreventDefault()ontouchmove, so that listener can't be passive — keep it on the frame, not the document. See Gestures for why the decision has to come before the gesture starts. - Animate discrete steps only. Buttons, double taps and keys get a short transition (none with reduced motion). Pinch and drag follow the fingers directly.
- Safari blurs scaled SVG under some CSS.
will-change: transform,matrix3d()and a transform transition can make Safari scale a bitmap of the SVG instead of redrawing it. The demo uses a 2Dtranslate() scale(), nowill-change, and a transition only for discrete steps; the blur from a transition clears once it ends.
Controls that get out of the way
Gestures cover most people, but buttons are still needed: not everyone knows the gestures, and pinching isn't possible for everyone. Buttons that sit on top of the diagram all the time cover part of it.
Video players solve the same problem: the controls appear when you move the mouse or tap the video, and fade out after a few seconds of no input. The demo does the same:
- Show the controls on mouse move over the diagram, on a tap, on keyboard focus, and on any zoom.
- Keep them while the pointer is over them, or while focus is inside the widget from the keyboard.
- Hide them after 2 seconds without input.
- While hidden, they ignore pointer events (
pointer-events: none). On a touchscreen the first tap only reveals them, so a tap can't press a button the reader couldn't see.
The percentage between the buttons doubles as the reset button.
Accessibility
- Keyboard. The frame is focusable: + and - zoom,
the arrow keys move a zoomed diagram, and 0 resets.
Instructions are linked with
aria-describedby. Unzoomed, the arrow keys keep scrolling the page. - Hidden controls appear on focus. Tabbing into the widget shows them and keeps them visible until focus leaves.
- Pinch needs a single-pointer alternative. WCAG 2.5.1 Pointer Gestures requires that multipoint gestures can also be done with a single pointer. The zoom buttons and double tap cover zooming.
- So does dragging. WCAG 2.5.7 Dragging Movements asks for a way to pan without dragging. The demo covers part of it: double tap zooms in at the tapped point, which brings that area into view. Full coverage would add pan buttons, or tap-to-centre while zoomed.
- The content still needs a text alternative. Zooming doesn't make a
diagram accessible. Give the SVG a
role="img"with a label, and put the important relationships in text next to it.
Installation
Install with the shadcn CLI, or copy the source below.
npx shadcn@latest add https://ui-patterns.stereobooster.com/r/pan-zoom.json"use client";
import * as React from "react";
import { Minus, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
type View = { s: number; x: number; y: number };
type Point = { x: number; y: number };
const MIN_SCALE = 1;
const MAX_SCALE = 8;
const BUTTON_STEP = 1.5;
const KEY_PAN = 60;
const SLOP = 10;
const DOUBLE_TAP_MS = 300;
const DOUBLE_TAP_DISTANCE = 24;
const HIDE_CONTROLS_MS = 2000;
const HINT_MS = 1500;
const MAX_WHEEL_DELTA = 50;
function prefersReducedMotion() {
return (
typeof matchMedia !== "undefined" &&
matchMedia("(prefers-reduced-motion: reduce)").matches
);
}
const IDENTITY: View = { s: 1, x: 0, y: 0 };
function clampView(v: View, w: number, h: number): View {
const s = Math.min(MAX_SCALE, Math.max(MIN_SCALE, v.s));
return {
s,
x: Math.min(0, Math.max(w - w * s, v.x)),
y: Math.min(0, Math.max(h - h * s, v.y)),
};
}
function rubberBand(overshoot: number, size: number) {
const d = Math.abs(overshoot);
return Math.sign(overshoot) * (1 - 1 / ((d * 0.55) / size + 1)) * size;
}
function zoomAt(v: View, factor: number, p: Point): View {
const s = Math.min(MAX_SCALE, Math.max(MIN_SCALE, v.s * factor));
const r = s / v.s;
return { s, x: p.x - (p.x - v.x) * r, y: p.y - (p.y - v.y) * r };
}
function center(points: Point[]): Point {
const x = points.reduce((sum, p) => sum + p.x, 0) / points.length;
const y = points.reduce((sum, p) => sum + p.y, 0) / points.length;
return { x, y };
}
function spread(points: Point[]) {
if (points.length < 2) return 0;
return Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
}
function isApple() {
return (
typeof navigator !== "undefined" &&
/Mac|iPhone|iPad/.test(navigator.userAgent)
);
}
export interface PanZoomProps {
mode?: "cooperative" | "greedy";
label: string;
children: React.ReactNode;
}
export function PanZoom({
mode = "cooperative",
label,
children,
}: PanZoomProps) {
const rootRef = React.useRef<HTMLDivElement>(null);
const viewportRef = React.useRef<HTMLDivElement>(null);
const contentRef = React.useRef<HTMLDivElement>(null);
const view = React.useRef<View>(IDENTITY);
const hideTimer = React.useRef<number>(undefined);
const hintTimer = React.useRef<number>(undefined);
const overControls = React.useRef(false);
const [scale, setScale] = React.useState(1);
const [controls, setControls] = React.useState(false);
const [hint, setHint] = React.useState<string | null>(null);
const instructionsId = React.useId();
const apply = React.useCallback(
(next: View, animate = false, elastic = false) => {
const viewport = viewportRef.current;
const content = contentRef.current;
if (!viewport || !content) return;
const w = viewport.clientWidth;
const h = viewport.clientHeight;
const clamped = clampView(next, w, h);
view.current = elastic ? { ...next, s: clamped.s } : clamped;
const v = elastic
? {
s: clamped.s,
x: clamped.x + rubberBand(next.x - clamped.x, w),
y: clamped.y + rubberBand(next.y - clamped.y, h),
}
: clamped;
content.style.transition =
animate && !prefersReducedMotion()
? "transform 250ms cubic-bezier(0.2, 0, 0, 1)"
: "";
content.style.transform = `translate(${v.x}px, ${v.y}px) scale(${v.s})`;
setScale(v.s);
},
[],
);
const showControls = React.useCallback(() => {
setControls(true);
window.clearTimeout(hideTimer.current);
hideTimer.current = window.setTimeout(() => {
if (overControls.current) return;
if (rootRef.current?.querySelector(":focus-visible")) return;
setControls(false);
}, HIDE_CONTROLS_MS);
}, []);
const showHint = React.useCallback((text: string) => {
setHint(text);
window.clearTimeout(hintTimer.current);
hintTimer.current = window.setTimeout(() => setHint(null), HINT_MS);
}, []);
const zoomBy = React.useCallback(
(factor: number) => {
const viewport = viewportRef.current;
if (!viewport) return;
const middle = {
x: viewport.clientWidth / 2,
y: viewport.clientHeight / 2,
};
apply(zoomAt(view.current, factor, middle), true);
showControls();
},
[apply, showControls],
);
const reset = React.useCallback(() => {
apply(IDENTITY, true);
showControls();
}, [apply, showControls]);
React.useEffect(() => {
const viewport = viewportRef.current;
if (!viewport) return;
const greedy = mode === "greedy";
const panFingers = greedy ? 1 : 2;
const local = (x: number, y: number): Point => {
const rect = viewport.getBoundingClientRect();
return { x: x - rect.left, y: y - rect.top };
};
const onWheel = (event: WheelEvent) => {
if (!greedy && !event.ctrlKey && !event.metaKey) {
showHint(
isApple() ? "Use ⌘ + scroll to zoom" : "Use Ctrl + scroll to zoom",
);
return;
}
event.preventDefault();
const unit =
event.deltaMode === 1
? 16
: event.deltaMode === 2
? viewport.clientHeight
: 1;
const delta = Math.max(
-MAX_WHEEL_DELTA,
Math.min(MAX_WHEEL_DELTA, event.deltaY * unit),
);
apply(
zoomAt(
view.current,
Math.exp(-delta * 0.01),
local(event.clientX, event.clientY),
),
);
showControls();
};
let lastTap: { t: number; p: Point } | null = null;
const tap = (p: Point, t: number) => {
showControls();
if (
lastTap &&
t - lastTap.t < DOUBLE_TAP_MS &&
Math.hypot(p.x - lastTap.p.x, p.y - lastTap.p.y) < DOUBLE_TAP_DISTANCE
) {
lastTap = null;
if (view.current.s > 1.01) apply(IDENTITY, true);
else apply(zoomAt(view.current, 2, p), true);
return;
}
lastTap = { t, p };
};
let press: {
id: number;
start: Point;
last: Point;
dragging: boolean;
mouse: boolean;
} | null = null;
const onPointerDown = (event: PointerEvent) => {
if (event.button !== 0) return;
const p = local(event.clientX, event.clientY);
const mouse = event.pointerType !== "touch";
if (mouse && (event.metaKey || event.altKey)) {
apply(zoomAt(view.current, event.altKey ? 0.5 : 2, p), true);
showControls();
return;
}
press = {
id: event.pointerId,
start: p,
last: p,
dragging: false,
mouse,
};
};
const onPointerMove = (event: PointerEvent) => {
if (event.pointerType === "mouse") showControls();
if (!press || press.id !== event.pointerId) return;
const p = local(event.clientX, event.clientY);
if (!press.dragging) {
if (Math.hypot(p.x - press.start.x, p.y - press.start.y) < SLOP) return;
press.dragging = true;
press.last = p;
if (press.mouse) {
viewport.setPointerCapture(event.pointerId);
viewport.style.cursor = "grabbing";
}
return;
}
if (!press.mouse) return;
const v = view.current;
apply(
{ ...v, x: v.x + p.x - press.last.x, y: v.y + p.y - press.last.y },
false,
true,
);
press.last = p;
};
const onPointerUp = (event: PointerEvent) => {
if (!press || press.id !== event.pointerId) return;
const ended = press;
press = null;
viewport.style.cursor = "";
if (ended.dragging) apply(view.current, true);
else tap(local(event.clientX, event.clientY), event.timeStamp);
};
const onPointerCancel = () => {
if (press?.dragging) apply(view.current, true);
press = null;
viewport.style.cursor = "";
};
let gesture: { c: Point; d: number; n: number } | null = null;
let oneFinger: Point | null = null;
const touchPoints = (event: TouchEvent) =>
Array.from(event.touches, (t) => local(t.clientX, t.clientY));
const onTouchStart = (event: TouchEvent) => {
gesture = null;
oneFinger = event.touches.length === 1 ? touchPoints(event)[0] : null;
};
const onTouchMove = (event: TouchEvent) => {
const points = touchPoints(event);
if (points.length >= panFingers && points.length <= 2) {
if (!event.cancelable) return;
event.preventDefault();
setHint(null);
const c = center(points);
const d = spread(points);
if (gesture && gesture.n === points.length) {
const v = view.current;
let next = {
...v,
x: v.x + c.x - gesture.c.x,
y: v.y + c.y - gesture.c.y,
};
if (gesture.d > 0 && d > 0) next = zoomAt(next, d / gesture.d, c);
apply(next, false, true);
showControls();
}
gesture = { c, d, n: points.length };
return;
}
if (!greedy && oneFinger && points.length === 1) {
const p = points[0];
if (Math.hypot(p.x - oneFinger.x, p.y - oneFinger.y) > SLOP) {
oneFinger = null;
showHint("Use two fingers to move and zoom");
}
}
};
const onTouchEnd = () => {
if (gesture) apply(view.current, true);
gesture = null;
oneFinger = null;
};
const onKeyDown = (event: KeyboardEvent) => {
if (!viewport.matches(":hover") || press) return;
if (event.metaKey) viewport.style.cursor = "zoom-in";
else if (event.altKey) viewport.style.cursor = "zoom-out";
};
const onKeyUp = () => {
if (!press) viewport.style.cursor = "";
};
const resize = new ResizeObserver(() => apply(view.current));
resize.observe(viewport);
viewport.addEventListener("wheel", onWheel, { passive: false });
viewport.addEventListener("pointerdown", onPointerDown);
viewport.addEventListener("pointermove", onPointerMove);
viewport.addEventListener("pointerup", onPointerUp);
viewport.addEventListener("pointercancel", onPointerCancel);
viewport.addEventListener("touchstart", onTouchStart, { passive: true });
viewport.addEventListener("touchmove", onTouchMove, { passive: false });
viewport.addEventListener("touchend", onTouchEnd);
viewport.addEventListener("touchcancel", onTouchEnd);
document.addEventListener("keydown", onKeyDown);
document.addEventListener("keyup", onKeyUp);
return () => {
resize.disconnect();
viewport.removeEventListener("wheel", onWheel);
viewport.removeEventListener("pointerdown", onPointerDown);
viewport.removeEventListener("pointermove", onPointerMove);
viewport.removeEventListener("pointerup", onPointerUp);
viewport.removeEventListener("pointercancel", onPointerCancel);
viewport.removeEventListener("touchstart", onTouchStart);
viewport.removeEventListener("touchmove", onTouchMove);
viewport.removeEventListener("touchend", onTouchEnd);
viewport.removeEventListener("touchcancel", onTouchEnd);
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener("keyup", onKeyUp);
window.clearTimeout(hideTimer.current);
window.clearTimeout(hintTimer.current);
};
}, [mode, apply, showControls, showHint]);
const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
const v = view.current;
const zoomed = v.s > 1.01;
const pan: Record<string, [number, number]> = {
ArrowLeft: [KEY_PAN, 0],
ArrowRight: [-KEY_PAN, 0],
ArrowUp: [0, KEY_PAN],
ArrowDown: [0, -KEY_PAN],
};
if (event.key === "+" || event.key === "=") zoomBy(BUTTON_STEP);
else if (event.key === "-") zoomBy(1 / BUTTON_STEP);
else if (event.key === "0") reset();
else if (zoomed && event.key in pan) {
const [dx, dy] = pan[event.key];
apply({ ...v, x: v.x + dx, y: v.y + dy }, true);
showControls();
} else return;
event.preventDefault();
};
const percent = Math.round(scale * 100);
const button =
"grid size-9 place-items-center rounded-full hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-white disabled:opacity-40";
return (
<div
ref={rootRef}
className="relative"
onFocus={(event) => {
if (event.target.matches(":focus-visible")) showControls();
}}
onBlur={showControls}
>
<div
ref={viewportRef}
role="group"
aria-label={label}
aria-describedby={instructionsId}
tabIndex={0}
onKeyDown={onKeyDown}
onDragStart={(event) => event.preventDefault()}
className={cn(
"bg-background relative overflow-hidden rounded-md border select-none focus-visible:outline-2 focus-visible:outline-offset-2",
mode === "greedy" ? "touch-none" : "touch-pan-x touch-pan-y",
"cursor-grab",
)}
>
<div
ref={contentRef}
className="origin-top-left [&_iframe]:pointer-events-none"
>
{children}
</div>
<div
aria-hidden
className={cn(
"pointer-events-none absolute inset-0 grid place-items-center bg-black/55 p-4 text-center text-sm font-medium text-white transition-opacity duration-300",
hint ? "opacity-100" : "opacity-0",
)}
>
{hint}
</div>
</div>
<p id={instructionsId} className="sr-only">
Plus and minus keys zoom, arrow keys move the zoomed diagram, 0 resets.
</p>
<div
onPointerEnter={() => (overControls.current = true)}
onPointerLeave={() => {
overControls.current = false;
showControls();
}}
className={cn(
"absolute right-2 bottom-2 flex items-center gap-0.5 rounded-full bg-neutral-900/80 p-0.5 text-white shadow-lg backdrop-blur transition-opacity duration-200",
controls ? "opacity-100" : "pointer-events-none opacity-0",
)}
>
<button
type="button"
aria-label="Zoom out"
className={button}
disabled={scale <= MIN_SCALE}
onClick={() => zoomBy(1 / BUTTON_STEP)}
>
<Minus className="size-4" aria-hidden />
</button>
<button
type="button"
aria-label={`Reset zoom, now ${percent}%`}
className="h-9 min-w-14 rounded-full px-2 text-xs font-medium tabular-nums hover:bg-white/15 focus-visible:outline-2 focus-visible:outline-white"
onClick={reset}
>
{percent}%
</button>
<button
type="button"
aria-label="Zoom in"
className={button}
disabled={scale >= MAX_SCALE}
onClick={() => zoomBy(BUTTON_STEP)}
>
<Plus className="size-4" aria-hidden />
</button>
</div>
</div>
);
}Usage:
<PanZoom label="Checkout system architecture, zoomable">
<ArchitectureDiagram />
</PanZoom>mode="greedy" exists only to show the scroll trap above; leave the
default.
The child can be inline SVG, an <img src="diagram.svg">, an <iframe>
or any other element. An iframe would take every pointer and wheel event
for its own document, so the component sets pointer-events: none on
it: it zooms and pans, but links inside it can't be clicked. An SVG in <img> stays sharp when zoomed, but it can't use the
page's CSS: currentColor and theme variables don't reach it, so for dark
mode the file needs its own prefers-color-scheme styles. Inline SVG
follows the page theme.
Or use a library
| library | cooperative by default | notes |
|---|---|---|
@beoe/pan-zoom | yes | the gesture table above, two-finger hint, Safari pixelation notes. No keyboard support or scale/position limits; the zoom factor is linear, so check Ctrl + mouse wheel |
| panzoom | no | zooms on every wheel event; beforeWheel can require a modifier key. Calls preventDefault() on all touch events in the container unless you pass onTouch |
| Google Maps | depends on gestureHandling | set gestureHandling: "cooperative" to always get the two-finger behaviour |
| Mapbox GL JS, MapLibre | no | cooperativeGestures: true |
Whatever you pick, check two things on a real phone and with a mouse wheel: can you scroll past the widget, and can you zoom it with one hand.
Sources
- Google Maps Platform: Cooperative gesture handling, Smart scrolling comes to mobile web maps
- Mapbox GL JS: Add cooperative gestures to a map
- WebKit: Bug 230545 — pinch to zoom should map to wheel with the Control key
- MDN:
touch-action,WheelEvent.deltaMode - W3C WCAG 2.2: 2.5.1 Pointer Gestures, 2.5.7 Dragging Movements
@beoe/pan-zoom