A dotted-glow-background component from Aceternity UI.
From Aceternity UI
1"use client";
2
3import React, { useEffect, useRef, useState } from "react";
4
5type DottedGlowBackgroundProps = {
6 className?: string;
7 /** distance between dot centers in pixels */
8 gap?: number;
9 /** base radius of each dot in CSS px */
10 radius?: number;
11 /** dot color (will pulse by alpha) */
12 color?: string;
13 /** optional dot color for dark mode */
14 darkColor?: string;
15 /** shadow/glow color for bright dots */
16 glowColor?: string;
17 /** optional glow color for dark mode */
18 darkGlowColor?: string;
19 /** optional CSS variable name for light dot color (e.g. --color-zinc-900) */
20 colorLightVar?: string;
21 /** optional CSS variable name for dark dot color (e.g. --color-zinc-100) */
22 colorDarkVar?: string;
23 /** optional CSS variable name for light glow color */
24 glowColorLightVar?: string;
25 /** optional CSS variable name for dark glow color */
26 glowColorDarkVar?: string;
27 /** global opacity for the whole layer */
28 opacity?: number;
29 /** background radial fade opacity (0 = transparent background) */
30 backgroundOpacity?: number;
31 /** minimum per-dot speed in rad/s */
32 speedMin?: number;
33 /** maximum per-dot speed in rad/s */
34 speedMax?: number;
35 /** global speed multiplier for all dots */
36 speedScale?: number;
37};
38
39/**
40 * Canvas-based dotted background that randomly glows and dims.
41 * - Uses a stable grid of dots.
42 * - Each dot gets its own phase + speed producing organic shimmering.
43 * - Handles high-DPI and resizes via ResizeObserver.
44 */
45export const DottedGlowBackground = ({
46 className,
47 gap = 12,
48 radius = 2,
49 color = "rgba(0,0,0,0.7)",
50 darkColor,
51 glowColor = "rgba(0, 170, 255, 0.85)",
52 darkGlowColor,
53 colorLightVar,
54 colorDarkVar,
55 glowColorLightVar,
56 glowColorDarkVar,
57 opacity = 0.6,
58 backgroundOpacity = 0,
59 speedMin = 0.4,
60 speedMax = 1.3,
61 speedScale = 1,
62}: DottedGlowBackgroundProps) => {
63 const canvasRef = useRef<HTMLCanvasElement | null>(null);
64 const containerRef = useRef<HTMLDivElement | null>(null);
65 const [resolvedColor, setResolvedColor] = useState<string>(color);
66 const [resolvedGlowColor, setResolvedGlowColor] = useState<string>(glowColor);
67
68 // Resolve CSS variable value from the container or root
69 const resolveCssVariable = (
70 el: Element,
71 variableName?: string,
72 ): string | null => {
73 if (!variableName) return null;
74 const normalized = variableName.startsWith("--")
75 ? variableName
76 : `--${variableName}`;
77 const fromEl = getComputedStyle(el as Element)
78 .getPropertyValue(normalized)
79 .trim();
80 if (fromEl) return fromEl;
81 const root = document.documentElement;
82 const fromRoot = getComputedStyle(root).getPropertyValue(normalized).trim();
83 return fromRoot || null;
84 };
85
86 const detectDarkMode = (): boolean => {
87 const root = document.documentElement;
88 if (root.classList.contains("dark")) return true;
89 if (root.classList.contains("light")) return false;
90 return (
91 window.matchMedia &&
92 window.matchMedia("(prefers-color-scheme: dark)").matches
93 );
94 };
95
96 // Keep resolved colors in sync with theme changes and prop updates
97 useEffect(() => {
98 const container = containerRef.current ?? document.documentElement;
99
100 const compute = () => {
101 const isDark = detectDarkMode();
102
103 let nextColor: string = color;
104 let nextGlow: string = glowColor;
105
106 if (isDark) {
107 const varDot = resolveCssVariable(container, colorDarkVar);
108 const varGlow = resolveCssVariable(container, glowColorDarkVar);
109 nextColor = varDot || darkColor || nextColor;
110 nextGlow = varGlow || darkGlowColor || nextGlow;
111 } else {
112 const varDot = resolveCssVariable(container, colorLightVar);
113 const varGlow = resolveCssVariable(container, glowColorLightVar);
114 nextColor = varDot || nextColor;
115 nextGlow = varGlow || nextGlow;
116 }
117
118 setResolvedColor(nextColor);
119 setResolvedGlowColor(nextGlow);
120 };
121
122 compute();
123
124 const mql = window.matchMedia
125 ? window.matchMedia("(prefers-color-scheme: dark)")
126 : null;
127 const handleMql = () => compute();
128 mql?.addEventListener?.("change", handleMql);
129
130 const mo = new MutationObserver(() => compute());
131 mo.observe(document.documentElement, {
132 attributes: true,
133 attributeFilter: ["class", "style"],
134 });
135
136 return () => {
137 mql?.removeEventListener?.("change", handleMql);
138 mo.disconnect();
139 };
140 }, [
141 color,
142 darkColor,
143 glowColor,
144 darkGlowColor,
145 colorLightVar,
146 colorDarkVar,
147 glowColorLightVar,
148 glowColorDarkVar,
149 ]);
150
151 useEffect(() => {
152 const el = canvasRef.current;
153 const container = containerRef.current;
154 if (!el || !container) return;
155
156 const ctx = el.getContext("2d");
157 if (!ctx) return;
158
159 let raf = 0;
160 let stopped = false;
161 let isVisible = true;
162
163 const dpr = Math.min(Math.max(1, window.devicePixelRatio || 1), 2);
164
165 const resize = () => {
166 const { width, height } = container.getBoundingClientRect();
167 el.width = Math.max(1, Math.floor(width * dpr));
168 el.height = Math.max(1, Math.floor(height * dpr));
169 el.style.width = `${Math.floor(width)}px`;
170 el.style.height = `${Math.floor(height)}px`;
171 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
172 };
173
174 const ro = new ResizeObserver(resize);
175 ro.observe(container);
176 resize();
177
178 // Precompute dot metadata for a medium-sized grid and regenerate on resize
179 let dots: { x: number; y: number; phase: number; speed: number }[] = [];
180
181 const regenDots = () => {
182 dots = [];
183 const { width, height } = container.getBoundingClientRect();
184 const cols = Math.ceil(width / gap) + 2;
185 const rows = Math.ceil(height / gap) + 2;
186 const min = Math.min(speedMin, speedMax);
187 const max = Math.max(speedMin, speedMax);
188 for (let i = -1; i < cols; i++) {
189 for (let j = -1; j < rows; j++) {
190 const x = i * gap + (j % 2 === 0 ? 0 : gap * 0.5); // offset every other row
191 const y = j * gap;
192 // Randomize phase and speed slightly per dot
193 const phase = Math.random() * Math.PI * 2;
194 const span = Math.max(max - min, 0);
195 const speed = min + Math.random() * span; // configurable rad/s
196 dots.push({ x, y, phase, speed });
197 }
198 }
199 };
200
201 const regenThrottled = () => {
202 regenDots();
203 };
204
205 regenDots();
206
207 let last = performance.now();
208
209 const draw = (now: number) => {
210 if (stopped) return;
211 if (!isVisible) {
212 raf = requestAnimationFrame(draw);
213 return;
214 }
215 const dt = (now - last) / 1000; // seconds
216 last = now;
217 const { width, height } = container.getBoundingClientRect();
218
219 ctx.clearRect(0, 0, el.width, el.height);
220 ctx.globalAlpha = opacity;
221
222 // optional subtle background fade for depth (defaults to 0 = transparent)
223 if (backgroundOpacity > 0) {
224 const grad = ctx.createRadialGradient(
225 width * 0.5,
226 height * 0.4,
227 Math.min(width, height) * 0.1,
228 width * 0.5,
229 height * 0.5,
230 Math.max(width, height) * 0.7,
231 );
232 grad.addColorStop(0, "rgba(0,0,0,0)");
233 grad.addColorStop(
234 1,
235 `rgba(0,0,0,${Math.min(Math.max(backgroundOpacity, 0), 1)})`,
236 );
237 ctx.fillStyle = grad as unknown as CanvasGradient;
238 ctx.fillRect(0, 0, width, height);
239 }
240
241 // animate dots
242 ctx.save();
243 ctx.fillStyle = resolvedColor;
244
245 const time = (now / 1000) * Math.max(speedScale, 0);
246 for (let i = 0; i < dots.length; i++) {
247 const d = dots[i];
248 // Linear triangle wave 0..1..0 for linear glow/dim
249 const mod = (time * d.speed + d.phase) % 2;
250 const lin = mod < 1 ? mod : 2 - mod; // 0..1..0
251 const a = 0.25 + 0.55 * lin; // 0.25..0.8 linearly
252
253 // draw glow when bright
254 if (a > 0.6) {
255 const glow = (a - 0.6) / 0.4; // 0..1
256 ctx.shadowColor = resolvedGlowColor;
257 ctx.shadowBlur = 6 * glow;
258 } else {
259 ctx.shadowColor = "transparent";
260 ctx.shadowBlur = 0;
261 }
262
263 ctx.globalAlpha = a * opacity;
264 ctx.beginPath();
265 ctx.arc(d.x, d.y, radius, 0, Math.PI * 2);
266 ctx.fill();
267 }
268 ctx.restore();
269
270 raf = requestAnimationFrame(draw);
271 };
272
273 const handleResize = () => {
274 resize();
275 regenThrottled();
276 };
277
278 const observer = new IntersectionObserver(
279 (entries) => {
280 isVisible = entries[0]?.isIntersecting ?? true;
281 },
282 { threshold: 0.1 },
283 );
284 observer.observe(container);
285
286 window.addEventListener("resize", handleResize);
287 raf = requestAnimationFrame(draw);
288
289 return () => {
290 stopped = true;
291 cancelAnimationFrame(raf);
292 window.removeEventListener("resize", handleResize);
293 observer.disconnect();
294 ro.disconnect();
295 };
296 }, [
297 gap,
298 radius,
299 resolvedColor,
300 resolvedGlowColor,
301 opacity,
302 backgroundOpacity,
303 speedMin,
304 speedMax,
305 speedScale,
306 ]);
307
308 return (
309 <div
310 ref={containerRef}
311 className={className}
312 style={{ position: "absolute", inset: 0 }}
313 >
314 <canvas
315 ref={canvasRef}
316 style={{ display: "block", width: "100%", height: "100%" }}
317 />
318 </div>
319 );
320};
321