Skip to content

Fisheye Grid

Fisheye grid: an infinite two-axis tile wall you drag with momentum, with a lens that swells tiles around the cursor.

  • Cursors & Interactions
  • Design tools
  • React only · 0 deps
  • 1 file
Full screen

Browser support · All evergreen browsers. Pointer, wheel and arrow keys pan; reduced motion removes momentum and the lens.

Install. One command, or copy the file.

$npx shadcn@latest add https://freedesignmd.com/r/fisheye-grid.json
  • Byte-identical to the preview
  • No Tailwind or config needed
  • SSR-safe · keyboard accessible
  • Respects reduced motion & transparency
components/interactions/fisheye-grid.tsx
1/**
2 * FisheyeGrid, an infinite, two-axis tile wall you drag around with
3 * momentum. A lens bulges the tiles around the pointer (or the centre when
4 * the pointer is away): nearby tiles swell and push their neighbours out,
5 * far tiles shrink back, like looking through a loupe.
6 *
7 * Props
8 * - count: number How many distinct tiles exist (wall repeats them).
9 * - renderTile: (i) => ReactNode Render tile content for index i (0..count-1).
10 * - tile?: number Tile size in px. Default 180 (130 under 640px).
11 * - gap?: number Gap in px. Default 14.
12 * - lens?: number Bulge strength 0–1. Default .55.
13 * - lensRadius?: number Lens radius in px. Default 300.
14 * - onSelect?: (i) => void Tile click (ignored after a drag).
15 * - label?: string Accessible name of the wall.
16 * - className / style Size the wall (it fills its box; give it a height).
17 * CSS vars: --fd-fg-radius (tile radius, default 16px), --fd-fg-bg.
18 *
19 * Implementation: a pooled grid of absolutely positioned tiles (only enough
20 * to cover the viewport + one ring) wraps around as you pan; every frame
21 * computes each tile's world cell, applies the lens displacement and writes
22 * one transform. Content only re-renders when a tile wraps to a new cell.
23 * Momentum uses exponential friction; pointer, wheel/trackpad and arrow keys pan.
24 * Accessibility: the wall is a focusable region (arrow keys pan, Enter picks
25 * the centre tile); tiles are aria-hidden duplicates, so pass a list of the
26 * real items elsewhere if they matter (the Demo has one).
27 * Reduced motion: no momentum glide and no lens.
28 * Browser support: all evergreen browsers.
29 *
30 * Demo images: /img/lux/*-800.webp and /img/people/p1,p3,p6.webp, included in the repo's
31 * public/img, copy them next to your page or swap in your own.
32 */
33import { useEffect, useRef, useState } from "react";
34import type { CSSProperties, KeyboardEvent, ReactNode } from "react";
35
36export interface FisheyeGridProps {
37 count: number;
38 renderTile: (i: number) => ReactNode;
39 tile?: number;
40 gap?: number;
41 lens?: number;
42 lensRadius?: number;
43 onSelect?: (i: number) => void;
44 label?: string;
45 className?: string;
46 style?: CSSProperties;
47}
48
49const cellIndex = (cx: number, cy: number, count: number) => {
50 // stable pseudo-random index per world cell, avoids visible repetition rows
51 let h = (cx * 374761393 + cy * 668265263) | 0;
52 h = Math.imul(h ^ (h >>> 13), 1274126177);
53 h ^= h >>> 16;
54 return ((h % count) + count) % count;
55};
56
57export function FisheyeGrid({ count, renderTile, tile = 180, gap = 14, lens = 0.55, lensRadius = 300, onSelect, label = "Tile wall", className, style }: FisheyeGridProps) {
58 const root = useRef<HTMLDivElement>(null);
59 const [dims, setDims] = useState({ cols: 0, rows: 0, size: tile });
60 // which content index each pool slot shows (state so React renders content)
61 const [slots, setSlots] = useState<number[]>([]);
62 const api = useRef<{ panBy: (x: number, y: number) => void; centerIndex: () => number }>({ panBy: () => {}, centerIndex: () => 0 });
63
64 useEffect(() => {
65 const el = root.current;
66 if (!el) return;
67 const measure = () => {
68 const size = el.clientWidth < 640 ? Math.round(tile * 0.72) : tile;
69 const pitch = size + gap;
70 const cols = Math.ceil(el.clientWidth / pitch) + 3;
71 const rows = Math.ceil(el.clientHeight / pitch) + 3;
72 setDims((d) => (d.cols === cols && d.rows === rows && d.size === size ? d : { cols, rows, size }));
73 };
74 measure();
75 const ro = new ResizeObserver(measure);
76 ro.observe(el);
77 return () => ro.disconnect();
78 }, [tile, gap]);
79
80 useEffect(() => {
81 const el = root.current;
82 const { cols, rows, size } = dims;
83 if (!el || !cols) return;
84 const tiles = Array.from(el.querySelectorAll<HTMLElement>(".fd-fg-tile"));
85 if (tiles.length !== cols * rows) return;
86 const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
87 const pitch = size + gap;
88 let W = el.clientWidth;
89 let H = el.clientHeight;
90 // camera
91 let ox = 0;
92 let oy = 0;
93 let vx = 0;
94 let vy = 0;
95 // lens centre (smoothed) and target
96 let lx = W / 2;
97 let ly = H / 2;
98 let tlx = lx;
99 let tly = ly;
100 let lensAmt = reduced ? 0 : lens;
101 let dragging = false;
102 let moved = 0;
103 let lastPX = 0;
104 let lastPY = 0;
105 let lastPT = 0;
106 let raf = 0;
107 let last = 0;
108 let visible = true;
109 const assigned = new Int32Array(cols * rows).fill(-1);
110 let pendingSlots: number[] | null = null;
111
112 const frame = (t: number) => {
113 raf = 0;
114 const dt = Math.min(0.05, (t - last) / 1000 || 0.016);
115 last = t;
116 if (!dragging && !reduced) {
117 const fr = Math.exp(-dt * 4.2);
118 ox += vx * dt;
119 oy += vy * dt;
120 vx *= fr;
121 vy *= fr;
122 if (Math.abs(vx) < 4) vx = 0;
123 if (Math.abs(vy) < 4) vy = 0;
124 }
125 const ls = 1 - Math.exp(-dt * 10);
126 lx += (tlx - lx) * ls;
127 ly += (tly - ly) * ls;
128
129 const R = el.clientWidth < 640 ? lensRadius * 0.7 : lensRadius;
130 let changed = false;
131 const next = pendingSlots ?? Array.from(assigned);
132 for (let j = 0; j < rows; j++) {
133 for (let i = 0; i < cols; i++) {
134 const k = j * cols + i;
135 // wrap pool slot into the visible window
136 const wx = ((((i * pitch + ox) % (cols * pitch)) + cols * pitch) % (cols * pitch)) - pitch * 1.5;
137 const wy = ((((j * pitch + oy) % (rows * pitch)) + rows * pitch) % (rows * pitch)) - pitch * 1.5;
138 // world cell of this slot
139 const cx = Math.round((wx - ox) / pitch);
140 const cy = Math.round((wy - oy) / pitch);
141 const idx = cellIndex(cx, cy, count);
142 if (assigned[k] !== idx) {
143 assigned[k] = idx;
144 next[k] = idx;
145 changed = true;
146 }
147 // lens: radial displacement + scale around (lx, ly)
148 const tx = wx + size / 2;
149 const ty = wy + size / 2;
150 const dx = tx - lx;
151 const dy = ty - ly;
152 const d = Math.hypot(dx, dy);
153 const g = Math.exp(-(d * d) / (2 * R * R));
154 const scale = 1 + lensAmt * 0.9 * g - lensAmt * 0.18 * (1 - g);
155 const push = 1 + lensAmt * 0.55 * g * (d / (R + 1)) * 1.6;
156 const px = lx + dx * push - size / 2;
157 const py = ly + dy * push - size / 2;
158 tiles[k].style.transform = `translate3d(${px.toFixed(1)}px,${py.toFixed(1)}px,0) scale(${scale.toFixed(4)})`;
159 tiles[k].style.zIndex = String(Math.round(g * 100));
160 }
161 }
162 if (changed) {
163 pendingSlots = next;
164 setSlots(next.slice());
165 pendingSlots = null;
166 }
167 const busy = dragging || Math.abs(vx) + Math.abs(vy) > 0 || Math.abs(tlx - lx) + Math.abs(tly - ly) > 0.3;
168 if (busy && visible && !document.hidden) raf = requestAnimationFrame(frame);
169 };
170 const kick = () => {
171 if (!raf && visible) {
172 last = performance.now();
173 raf = requestAnimationFrame(frame);
174 }
175 };
176
177 const onDown = (e: PointerEvent) => {
178 if (e.button !== 0) return;
179 dragging = true;
180 moved = 0;
181 vx = vy = 0;
182 lastPX = e.clientX;
183 lastPY = e.clientY;
184 lastPT = performance.now();
185 el.setPointerCapture(e.pointerId);
186 el.setAttribute("data-dragging", "");
187 kick();
188 };
189 const onMove = (e: PointerEvent) => {
190 const r = el.getBoundingClientRect();
191 if (e.pointerType !== "touch") {
192 tlx = e.clientX - r.left;
193 tly = e.clientY - r.top;
194 }
195 if (dragging) {
196 const now = performance.now();
197 const dx = e.clientX - lastPX;
198 const dy = e.clientY - lastPY;
199 const dtt = Math.max(1, now - lastPT) / 1000;
200 ox += dx;
201 oy += dy;
202 moved += Math.abs(dx) + Math.abs(dy);
203 // smoothed release velocity
204 vx = vx * 0.6 + (dx / dtt) * 0.4;
205 vy = vy * 0.6 + (dy / dtt) * 0.4;
206 lastPX = e.clientX;
207 lastPY = e.clientY;
208 lastPT = now;
209 }
210 kick();
211 };
212 const onUp = (e: PointerEvent) => {
213 if (!dragging) return;
214 dragging = false;
215 el.removeAttribute("data-dragging");
216 if (performance.now() - lastPT > 80) vx = vy = 0;
217 if (moved < 6) {
218 vx = vy = 0;
219 const t = (e.target as Element | null)?.closest?.(".fd-fg-tile") as HTMLElement | null;
220 if (t) onSelectRef.current?.(Number(t.dataset.idx));
221 }
222 kick();
223 };
224 const onLeave = () => {
225 tlx = W / 2;
226 tly = H / 2;
227 kick();
228 };
229 const onWheel = (e: WheelEvent) => {
230 e.preventDefault();
231 ox -= e.deltaX;
232 oy -= e.deltaY;
233 kick();
234 };
235 const onResize = () => {
236 W = el.clientWidth;
237 H = el.clientHeight;
238 tlx = W / 2;
239 tly = H / 2;
240 kick();
241 };
242 const io = new IntersectionObserver((es) => {
243 visible = es.some((x) => x.isIntersecting);
244 if (visible) kick();
245 });
246 io.observe(el);
247 api.current = {
248 panBy: (x: number, y: number) => {
249 if (reduced) {
250 ox += x;
251 oy += y;
252 } else {
253 vx += x * 5;
254 vy += y * 5;
255 }
256 kick();
257 },
258 centerIndex: () => {
259 let best = 0;
260 let bd = Infinity;
261 tiles.forEach((t) => {
262 const r = t.getBoundingClientRect();
263 const er = el.getBoundingClientRect();
264 const d = Math.hypot(r.left + r.width / 2 - er.left - W / 2, r.top + r.height / 2 - er.top - H / 2);
265 if (d < bd) {
266 bd = d;
267 best = Number(t.dataset.idx);
268 }
269 });
270 return best;
271 },
272 };
273 lensAmt = reduced ? 0 : lens;
274
275 el.addEventListener("pointerdown", onDown);
276 el.addEventListener("pointermove", onMove);
277 el.addEventListener("pointerup", onUp);
278 el.addEventListener("pointercancel", onUp);
279 el.addEventListener("pointerleave", onLeave);
280 el.addEventListener("wheel", onWheel, { passive: false });
281 window.addEventListener("resize", onResize);
282 // centre the wall on a tile, then draw
283 ox = W / 2 - size / 2 - pitch * 1.5 + pitch * 0.5;
284 oy = H / 2 - size / 2 - pitch * 1.5 + pitch * 0.5;
285 kick();
286 return () => {
287 cancelAnimationFrame(raf);
288 io.disconnect();
289 el.removeEventListener("pointerdown", onDown);
290 el.removeEventListener("pointermove", onMove);
291 el.removeEventListener("pointerup", onUp);
292 el.removeEventListener("pointercancel", onUp);
293 el.removeEventListener("pointerleave", onLeave);
294 el.removeEventListener("wheel", onWheel);
295 window.removeEventListener("resize", onResize);
296 };
297 }, [dims, gap, lens, lensRadius, count]);
298
299 const onSelectRef = useRef(onSelect);
300 onSelectRef.current = onSelect;
301
302 const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
303 const step = dims.size + gap;
304 const map: Record<string, [number, number]> = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] };
305 if (map[e.key]) {
306 e.preventDefault();
307 api.current.panBy(...map[e.key]);
308 } else if (e.key === "Enter" || e.key === " ") {
309 e.preventDefault();
310 onSelect?.(api.current.centerIndex());
311 }
312 };
313
314 const n = dims.cols * dims.rows;
315 return (
316 <div
317 ref={root}
318 className={`fd-fg${className ? " " + className : ""}`}
319 style={{ ...style, ["--fd-fg-size" as string]: `${dims.size}px` }}
320 role="region"
321 aria-roledescription="pannable wall"
322 aria-label={`${label}. Drag or use arrow keys to pan, Enter to pick the centre tile.`}
323 tabIndex={0}
324 onKeyDown={onKey}
325 >
326 <style>{css}</style>
327 {Array.from({ length: n }, (_, k) => {
328 const idx = slots[k] ?? k % count;
329 return (
330 <div key={k} className="fd-fg-tile" data-idx={idx} aria-hidden="true">
331 {renderTile(idx)}
332 </div>
333 );
334 })}
335 </div>
336 );
337}
338
339const css = `
340.fd-fg,.fd-fg *,.fd-fg *::before,.fd-fg *::after{box-sizing:border-box}
341.fd-fg{--fd-fg-radius:16px;--fd-fg-bg:#0D0D10;position:relative;display:block;margin:0;padding:0;overflow:hidden;background:var(--fd-fg-bg);
342 cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;outline:0}
343.fd-fg[data-dragging]{cursor:grabbing}
344.fd-fg:focus-visible{box-shadow:inset 0 0 0 2px rgba(10,132,255,.8)}
345.fd-fg-tile{position:absolute;left:0;top:0;width:var(--fd-fg-size);height:var(--fd-fg-size);margin:0;padding:0;border-radius:var(--fd-fg-radius);overflow:hidden;
346 will-change:transform;transform-origin:50% 50%;contain:layout paint;box-shadow:0 10px 30px -14px rgba(0,0,0,.6)}
347`;
348
349/* ───────────────────────────── demo ───────────────────────────── */
350
351const TILES = [
352 ["#ffffff", "#e9e9ec"],
353 ["#f4efe9", "#e2d9cf"],
354 ["#eceff4", "#d6dce8"],
355 ["#f1ecf3", "#ddd3e3"],
356 ["#ecf1ee", "#d3dfd8"],
357 ["#f5ede8", "#e6d3c9"],
358 ["#eeeeee", "#d9d9dc"],
359 ["#eef0f5", "#dadfec"],
360];
361
362export function Demo() {
363 return (
364 <div className="fd-fgd">
365 <style>{demoCss}</style>
366 <FisheyeGrid
367 count={TILES.length * 2}
368 label="Tile wall"
369 className="fd-fgd-wall"
370 renderTile={(i) => {
371 const [a, b] = TILES[i % TILES.length];
372 return <div className="fd-fgd-tile" style={{ background: `linear-gradient(150deg,${a},${b})` }} />;
373 }}
374 />
375 </div>
376 );
377}
378
379const demoCss = `
380.fd-fgd,.fd-fgd *,.fd-fgd *::before,.fd-fgd *::after{box-sizing:border-box}
381.fd-fgd{position:relative;height:100vh;min-height:420px;width:100%;margin:0;padding:0;overflow:hidden;background:#f2f2f2;color:#1d1d1f;font:400 15px/1.4 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;letter-spacing:normal}
382.fd-fgd .fd-fgd-wall{--fd-fg-bg:#f2f2f2;--fd-fg-radius:22px;position:absolute;inset:0}
383.fd-fgd .fd-fg-tile{box-shadow:0 8px 22px -14px rgba(0,0,0,.28),0 0 0 1px rgba(0,0,0,.03)}
384.fd-fgd-tile{position:absolute;inset:0;margin:0;padding:0}
385`;

More Cursors & Interactions. Same file contract.

Image Trail, interactions preview: Image trail cursor effect: cards spawn along the cursor path, pop in with a tilt and fall away

Image Trail

Image trail cursor effect: cards spawn along the cursor path, pop in with a tilt and fall away. A gallery you move through.

Custom Cursor, interactions preview: Custom cursor for React: a dot and a spring-lagged ring that morph into labels like View, Drag or Play and…

Custom Cursor

Custom cursor for React: a dot and a spring-lagged ring that morph into labels like View, Drag or Play and snap to buttons.

Magnetic Dock, interactions preview: macOS-style dock for React: icons swell with a gaussian falloff, labels float up, launches bounce and running…

Magnetic Dock

macOS-style dock for React: icons swell with a gaussian falloff, labels float up, launches bounce and running apps get a dot.

Questions about Fisheye Grid

Run npx shadcn@latest add https://freedesignmd.com/r/fisheye-grid.json, or open the page and copy the file into your project. It has zero dependencies besides React. What you copy is the exact file that renders the live demo.

Fisheye grid: an infinite two-axis tile wall you drag with momentum, with a lens that swells tiles around the cursor. It is a free, MIT-licensed React cursors & interactions component from the freedesignmd library.

Yes. It is free and MIT-licensed, use, modify and ship it in personal and commercial projects without attribution.

All evergreen browsers. Pointer, wheel and arrow keys pan; reduced motion removes momentum and the lens.

Yes. It is a plain React component with its own styles, so it runs in Next.js, Vite, Remix and Lovable projects, and it needs no Tailwind setup. It has zero dependencies besides React.