Loading…
← All components

Cursors · Optics

Glass Lens

A magnifying lens that refracts the page under it, bending its rim with RGB chromatic aberration.

Move over the words, then the buttons.

Read the docsdata-cursor-text
<GlassLensRefractionCursor />Live

Customize

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add glass-lens
01

Install

The 3D packages this component is built on.

Nothing to install: React is all it needs.

02

Add the component

One self-contained file: create components/GlassLensRefractionCursor.tsx and paste it in.

components/GlassLensRefractionCursor.tsx
1"use client";
2
3import { memo, useEffect, useId, useRef, useState, type CSSProperties, type RefObject } from "react";
4
5/** What counts as interactive: the cursors react when the pointer is over one of these. */
6const INTERACTIVE_SELECTOR =
7 "a, button, [role='button'], input, select, textarea, label, summary, [data-cursor], [data-cursor-text], [data-cursor-hover]";
8
9/** A layer pinned to the top-left corner and moved with transforms (no layout, no repaint). */
10const FOLLOWER_STYLE: CSSProperties = {
11 position: "fixed",
12 top: 0,
13 left: 0,
14 pointerEvents: "none",
15 zIndex: 9999,
16 willChange: "transform",
17};
18
19/**
20 * False on touch screens (`pointer: coarse`) and during server rendering: the custom cursor is not
21 * drawn and the native cursor is left alone. Follows the media query live (tablet + mouse…).
22 */
23function useCursorEnabled() {
24 const [enabled, setEnabled] = useState(false);
25 useEffect(() => {
26 const query = window.matchMedia("(pointer: coarse)");
27 const sync = () => setEnabled(!query.matches);
28 sync();
29 query.addEventListener("change", sync);
30 return () => query.removeEventListener("change", sync);
31 }, []);
32 return enabled;
33}
34
35/** Hides the system cursor on the whole page while `active` (restored on unmount). */
36function useHideNativeCursor(active: boolean) {
37 useEffect(() => {
38 if (!active) return undefined;
39 const style = document.createElement("style");
40 style.setAttribute("data-custom-cursor", "");
41 style.textContent = "*, *::before, *::after { cursor: none !important; }";
42 document.head.appendChild(style);
43 return () => style.remove();
44 }, [active]);
45}
46
47interface CursorPointer {
48 /** Position in CSS pixels, relative to the viewport. */
49 x: number;
50 y: number;
51 /** Smoothed velocity, in CSS pixels per second. */
52 vx: number;
53 vy: number;
54 speed: number;
55 /** False until the first move, and while the pointer is outside the window. */
56 visible: boolean;
57 down: boolean;
58 /** The interactive element under the pointer (closest match of the selector), or null. */
59 target: HTMLElement | null;
60 /** Incremented on every press, to trigger click effects. */
61 clicks: number;
62}
63
64/**
65 * Tracks the pointer through window listeners and returns a ref read inside the animation loop:
66 * moving the mouse never re-renders React. All listeners are removed on unmount.
67 */
68function useCursorPointer(enabled: boolean, selector = INTERACTIVE_SELECTOR): RefObject<CursorPointer> {
69 const pointer = useRef<CursorPointer>({ x: -100, y: -100, vx: 0, vy: 0, speed: 0, visible: false, down: false, target: null, clicks: 0 });
70
71 useEffect(() => {
72 if (!enabled) return undefined;
73 let last = performance.now();
74 const p = pointer.current;
75 const pick = (event: PointerEvent) => {
76 const el = event.target instanceof Element ? event.target.closest(selector) : null;
77 p.target = el instanceof HTMLElement ? el : null;
78 };
79 const move = (event: PointerEvent) => {
80 if (event.pointerType === "touch") return;
81 const now = performance.now();
82 const dt = Math.max(1, now - last) / 1000;
83 last = now;
84 if (p.visible) {
85 // Smoothed: one jittery event must not make the effects jump
86 p.vx = p.vx * 0.6 + ((event.clientX - p.x) / dt) * 0.4;
87 p.vy = p.vy * 0.6 + ((event.clientY - p.y) / dt) * 0.4;
88 }
89 p.x = event.clientX;
90 p.y = event.clientY;
91 p.visible = true;
92 pick(event);
93 };
94 const down = (event: PointerEvent) => {
95 if (event.pointerType === "touch") return;
96 p.down = true;
97 p.clicks += 1;
98 pick(event);
99 };
100 const up = () => {
101 p.down = false;
102 };
103 const leave = () => {
104 p.visible = false;
105 p.down = false;
106 };
107 window.addEventListener("pointermove", move, { passive: true });
108 window.addEventListener("pointerdown", down, { passive: true });
109 window.addEventListener("pointerup", up, { passive: true });
110 document.documentElement.addEventListener("pointerleave", leave);
111 window.addEventListener("blur", leave);
112 return () => {
113 window.removeEventListener("pointermove", move);
114 window.removeEventListener("pointerdown", down);
115 window.removeEventListener("pointerup", up);
116 document.documentElement.removeEventListener("pointerleave", leave);
117 window.removeEventListener("blur", leave);
118 };
119 }, [enabled, selector]);
120
121 return pointer;
122}
123
124/**
125 * requestAnimationFrame loop: `frame(dt, time)` runs every frame (dt in seconds, capped) while
126 * `enabled`; the browser pauses it in background tabs. The latest callback is always used.
127 */
128function useAnimationFrame(enabled: boolean, frame: (dt: number, time: number) => void) {
129 const frameRef = useRef(frame);
130 useEffect(() => {
131 frameRef.current = frame;
132 });
133 useEffect(() => {
134 if (!enabled) return undefined;
135 let id = 0;
136 let last = performance.now();
137 const tick = (now: number) => {
138 const dt = Math.min((now - last) / 1000, 1 / 20);
139 last = now;
140 frameRef.current(dt, now / 1000);
141 id = requestAnimationFrame(tick);
142 };
143 id = requestAnimationFrame(tick);
144 return () => cancelAnimationFrame(id);
145 }, [enabled]);
146}
147
148/**
149 * Velocity only changes on pointer events: call this once per frame so it fades out when the pointer
150 * stops, and read `speed` afterwards.
151 */
152function settlePointer(p: CursorPointer, dt: number) {
153 const k = Math.exp(-10 * dt);
154 p.vx *= k;
155 p.vy *= k;
156 p.speed = Math.hypot(p.vx, p.vy);
157}
158
159/** Exponential smoothing factor for a frame: frame-rate independent `lerp`. */
160const damp = (lambda: number, dt: number) => 1 - Math.exp(-lambda * dt);
161
162export interface GlassLensCursorProps {
163 /** Radius of the lens, in CSS pixels. Default 70. */
164 radius?: number;
165 /** Magnification at the center of the lens. Default 1.6. */
166 zoomFactor?: number;
167 /** RGB split toward the rim of the lens (0 = none). Default 1. */
168 chromaticIntensity?: number;
169 /** Lens scale over links and buttons. Default 1.25. */
170 hoverScale?: number;
171 /** Hide the system cursor while the lens is shown. Default true. */
172 hideNativeCursor?: boolean;
173}
174
175/**
176 * Displacement map of a magnifying lens: each pixel stores (in red / green) where the lens samples the
177 * page behind it — pulled toward the center (magnification), bent harder near the rim (barrel).
178 */
179function createLensMap(radius: number, zoom: number) {
180 const size = Math.round(radius * 2);
181 const canvas = document.createElement("canvas");
182 canvas.width = canvas.height = size;
183 const ctx = canvas.getContext("2d")!;
184 const image = ctx.createImageData(size, size);
185 const scale = radius; // must match the feDisplacementMap scale
186 for (let y = 0; y < size; y++) {
187 for (let x = 0; x < size; x++) {
188 const dx = (x + 0.5 - radius) / radius;
189 const dy = (y + 0.5 - radius) / radius;
190 const d = Math.min(Math.hypot(dx, dy), 1);
191 // Sample closer to the center (zoom), plus a curved rim
192 const pull = (1 - 1 / zoom) + d ** 4 * 0.18;
193 const ox = -dx * radius * pull;
194 const oy = -dy * radius * pull;
195 const i = (y * size + x) * 4;
196 image.data[i] = Math.round(Math.min(255, Math.max(0, (0.5 + ox / scale) * 255)));
197 image.data[i + 1] = Math.round(Math.min(255, Math.max(0, (0.5 + oy / scale) * 255)));
198 image.data[i + 2] = 128;
199 image.data[i + 3] = 255;
200 }
201 }
202 ctx.putImageData(image, 0, 0);
203 return canvas.toDataURL();
204}
205
206/**
207 * A circular glass lens that magnifies whatever is under it, bending the rim and splitting the colors
208 * (chromatic aberration). The refraction is an SVG displacement filter applied as a backdrop filter —
209 * Chromium browsers; elsewhere the lens falls back to a clear glass bead (blur-free, saturated).
210 */
211function GlassLensRefractionCursor({
212 radius = 70,
213 zoomFactor = 1.6,
214 chromaticIntensity = 1,
215 hoverScale = 1.25,
216 hideNativeCursor = true,
217}: GlassLensCursorProps) {
218 const enabled = useCursorEnabled();
219 const pointer = useCursorPointer(enabled);
220 useHideNativeCursor(enabled && hideNativeCursor);
221 const lens = useRef<HTMLDivElement>(null);
222 const filterId = `lens-${useId().replace(/[^a-zA-Z0-9-]/g, "")}`;
223 const [map, setMap] = useState<string | null>(null);
224 const [refraction, setRefraction] = useState(false);
225 const state = useRef({ x: -500, y: -500, scale: 1, opacity: 0 });
226
227 useEffect(() => {
228 if (!enabled) return;
229 // SVG filters in backdrop-filter are a Chromium feature
230 const brands = (navigator as Navigator & { userAgentData?: { brands: { brand: string }[] } }).userAgentData?.brands ?? [];
231 setRefraction(brands.some((b) => /Chromium|Google Chrome|Microsoft Edge/.test(b.brand)));
232 setMap(createLensMap(radius, Math.max(zoomFactor, 1)));
233 }, [enabled, radius, zoomFactor]);
234
235 useAnimationFrame(enabled, (dt) => {
236 const el = lens.current;
237 const p = pointer.current;
238 if (!el) return;
239 settlePointer(p, dt);
240 const s = state.current;
241 const k = damp(18, dt);
242 s.x += (p.x - s.x) * k;
243 s.y += (p.y - s.y) * k;
244 s.scale += ((p.target ? hoverScale : p.down ? 0.9 : 1) - s.scale) * damp(10, dt);
245 s.opacity += ((p.visible ? 1 : 0) - s.opacity) * damp(10, dt);
246 el.style.opacity = s.opacity.toFixed(3);
247 el.style.transform = `translate3d(${s.x - radius}px, ${s.y - radius}px, 0) scale(${s.scale})`;
248 });
249
250 if (!enabled) return null;
251 const d = radius * 2;
252 const split = radius * 0.06 * chromaticIntensity;
253 const channel = (r: number, g: number, b: number) => `${r} 0 0 0 0 0 ${g} 0 0 0 0 0 ${b} 0 0 0 0 0 1 0`;
254 return (
255 <>
256 <svg aria-hidden="true" width="0" height="0" style={{ position: "absolute" }}>
257 <defs>
258 <filter id={filterId} x="0" y="0" width={d} height={d} filterUnits="userSpaceOnUse" colorInterpolationFilters="sRGB">
259 {map && <feImage href={map} x="0" y="0" width={d} height={d} result="map" preserveAspectRatio="none" />}
260 {/* Each color channel is bent by a slightly different amount: the rim splits into RGB */}
261 <feDisplacementMap in="SourceGraphic" in2="map" scale={radius + split} xChannelSelector="R" yChannelSelector="G" result="dr" />
262 <feColorMatrix in="dr" type="matrix" values={channel(1, 0, 0)} result="r" />
263 <feDisplacementMap in="SourceGraphic" in2="map" scale={radius} xChannelSelector="R" yChannelSelector="G" result="dg" />
264 <feColorMatrix in="dg" type="matrix" values={channel(0, 1, 0)} result="g" />
265 <feDisplacementMap in="SourceGraphic" in2="map" scale={Math.max(1, radius - split)} xChannelSelector="R" yChannelSelector="G" result="db" />
266 <feColorMatrix in="db" type="matrix" values={channel(0, 0, 1)} result="b" />
267 <feBlend in="r" in2="g" mode="screen" result="rg" />
268 <feBlend in="rg" in2="b" mode="screen" />
269 </filter>
270 </defs>
271 </svg>
272 <div
273 ref={lens}
274 aria-hidden="true"
275 style={{
276 ...FOLLOWER_STYLE,
277 width: d,
278 height: d,
279 borderRadius: "50%",
280 opacity: 0,
281 transformOrigin: "50% 50%",
282 // Chromium treats the -webkit- property as an alias: only set it for the Safari fallback
283 ...(refraction && map
284 ? { backdropFilter: `url(#${filterId})` }
285 : { backdropFilter: "saturate(1.6) brightness(1.08)", WebkitBackdropFilter: "saturate(1.6) brightness(1.08)" }),
286 border: "1px solid rgba(255,255,255,0.35)",
287 boxShadow: [
288 "inset 0 2px 6px rgba(255,255,255,0.35)",
289 "inset 0 -10px 24px rgba(0,0,0,0.25)",
290 `inset ${split * 0.6}px 0 ${split}px rgba(255,40,80,${0.14 * chromaticIntensity})`,
291 `inset ${-split * 0.6}px 0 ${split}px rgba(40,200,255,${0.14 * chromaticIntensity})`,
292 "0 12px 30px rgba(0,0,0,0.25)",
293 ].join(", "),
294 }}
295 />
296 </>
297 );
298}
299
300export default memo(GlassLensRefractionCursor);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import GlassLensRefractionCursor from "@/components/GlassLensRefractionCursor";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <GlassLensRefractionCursor
8 radius={70}
9 zoomFactor={1.6}
10 chromaticIntensity={1}
11 />
12 </div>
13 );
14}
Next componentElastic Blob→