A webcam-pixel-grid component from Aceternity UI.
From Aceternity UI
1"use client";
2import React, { useRef, useEffect, useState, useCallback } from "react";
3import { cn } from "@/lib/utils";
4
5type WebcamPixelGridProps = {
6 /** Number of columns in the grid */
7 gridCols?: number;
8 /** Number of rows in the grid */
9 gridRows?: number;
10 /** Maximum elevation for motion detection */
11 maxElevation?: number;
12 /** Motion sensitivity (0-1) */
13 motionSensitivity?: number;
14 /** Smoothing factor for elevation transitions */
15 elevationSmoothing?: number;
16 /** Color mode: 'webcam' uses actual colors, 'monochrome' uses single color */
17 colorMode?: "webcam" | "monochrome";
18 /** Base color when in monochrome mode */
19 monochromeColor?: string;
20 /** Background color */
21 backgroundColor?: string;
22 /** Whether to mirror the webcam feed */
23 mirror?: boolean;
24 /** Gap between cells (0-1, fraction of cell size) */
25 gapRatio?: number;
26 /** Invert the colors */
27 invertColors?: boolean;
28 /** Darken factor (0-1, 0 = no darkening, 1 = fully dark) */
29 darken?: number;
30 /** Border color for cells */
31 borderColor?: string;
32 /** Border opacity (0-1) */
33 borderOpacity?: number;
34 /** Additional class name */
35 className?: string;
36 /** Callback when webcam access is denied */
37 onWebcamError?: (error: Error) => void;
38 /** Callback when webcam is ready */
39 onWebcamReady?: () => void;
40};
41
42type PixelData = {
43 r: number;
44 g: number;
45 b: number;
46 motion: number;
47 targetElevation: number;
48 currentElevation: number;
49};
50
51export const WebcamPixelGrid: React.FC<WebcamPixelGridProps> = ({
52 gridCols = 64,
53 gridRows = 48,
54 maxElevation = 15,
55 motionSensitivity = 0.4,
56 elevationSmoothing = 0.1,
57 colorMode = "webcam",
58 monochromeColor = "#00ff88",
59 backgroundColor = "#0a0a0a",
60 mirror = true,
61 gapRatio = 0.1,
62 invertColors = false,
63 darken = 0,
64 borderColor = "#ffffff",
65 borderOpacity = 0.08,
66 className,
67 onWebcamError,
68 onWebcamReady,
69}) => {
70 const videoRef = useRef<HTMLVideoElement>(null);
71 const processingCanvasRef = useRef<HTMLCanvasElement>(null);
72 const displayCanvasRef = useRef<HTMLCanvasElement>(null);
73 const previousFrameRef = useRef<Uint8ClampedArray | null>(null);
74 const pixelDataRef = useRef<PixelData[][]>([]);
75 const animationRef = useRef<number>(0);
76 const [isReady, setIsReady] = useState(false);
77 const [error, setError] = useState<string | null>(null);
78 const [showErrorPopup, setShowErrorPopup] = useState(true);
79
80 // Parse monochrome color
81 const monoRGB = React.useMemo(() => {
82 const hex = monochromeColor.replace("#", "");
83 return {
84 r: parseInt(hex.slice(0, 2), 16),
85 g: parseInt(hex.slice(2, 4), 16),
86 b: parseInt(hex.slice(4, 6), 16),
87 };
88 }, [monochromeColor]);
89
90 // Parse border color
91 const borderRGB = React.useMemo(() => {
92 const hex = borderColor.replace("#", "");
93 return {
94 r: parseInt(hex.slice(0, 2), 16),
95 g: parseInt(hex.slice(2, 4), 16),
96 b: parseInt(hex.slice(4, 6), 16),
97 };
98 }, [borderColor]);
99
100 // Initialize pixel data
101 useEffect(() => {
102 pixelDataRef.current = Array.from({ length: gridRows }, () =>
103 Array.from({ length: gridCols }, () => ({
104 r: 30,
105 g: 30,
106 b: 30,
107 motion: 0,
108 targetElevation: 0,
109 currentElevation: 0,
110 })),
111 );
112 }, [gridCols, gridRows]);
113
114 const streamRef = useRef<MediaStream | null>(null);
115
116 // Request camera access
117 const requestCameraAccess = useCallback(async () => {
118 try {
119 const stream = await navigator.mediaDevices.getUserMedia({
120 video: {
121 width: { ideal: 640 },
122 height: { ideal: 480 },
123 facingMode: "user",
124 },
125 });
126
127 streamRef.current = stream;
128
129 if (videoRef.current) {
130 videoRef.current.srcObject = stream;
131 await videoRef.current.play();
132 setIsReady(true);
133 setError(null);
134 setShowErrorPopup(false);
135 onWebcamReady?.();
136 }
137 } catch (err) {
138 const error =
139 err instanceof Error ? err : new Error("Webcam access denied");
140 setError(error.message);
141 onWebcamError?.(error);
142 }
143 }, [onWebcamError, onWebcamReady]);
144
145 // Initialize webcam on mount
146 useEffect(() => {
147 requestCameraAccess();
148
149 return () => {
150 if (streamRef.current) {
151 streamRef.current.getTracks().forEach((track) => track.stop());
152 }
153 };
154 }, [requestCameraAccess]);
155
156 // Main render loop
157 const render = useCallback(() => {
158 const video = videoRef.current;
159 const processingCanvas = processingCanvasRef.current;
160 const displayCanvas = displayCanvasRef.current;
161
162 if (!video || !processingCanvas || !displayCanvas || video.readyState < 2) {
163 animationRef.current = requestAnimationFrame(render);
164 return;
165 }
166
167 const procCtx = processingCanvas.getContext("2d", {
168 willReadFrequently: true,
169 });
170 const dispCtx = displayCanvas.getContext("2d");
171
172 if (!procCtx || !dispCtx) {
173 animationRef.current = requestAnimationFrame(render);
174 return;
175 }
176
177 // Set processing canvas size to grid dimensions
178 processingCanvas.width = gridCols;
179 processingCanvas.height = gridRows;
180
181 // Draw video to processing canvas (scaled down)
182 procCtx.save();
183 if (mirror) {
184 procCtx.scale(-1, 1);
185 procCtx.drawImage(video, -gridCols, 0, gridCols, gridRows);
186 } else {
187 procCtx.drawImage(video, 0, 0, gridCols, gridRows);
188 }
189 procCtx.restore();
190
191 // Get pixel data
192 const imageData = procCtx.getImageData(0, 0, gridCols, gridRows);
193 const currentData = imageData.data;
194 const previousData = previousFrameRef.current;
195
196 // Update pixel data with motion detection
197 const pixels = pixelDataRef.current;
198 for (let row = 0; row < gridRows; row++) {
199 for (let col = 0; col < gridCols; col++) {
200 const idx = (row * gridCols + col) * 4;
201 const r = currentData[idx];
202 const g = currentData[idx + 1];
203 const b = currentData[idx + 2];
204
205 const pixel = pixels[row]?.[col];
206 if (!pixel) continue;
207
208 // Calculate motion
209 let motion = 0;
210 if (previousData) {
211 const prevR = previousData[idx];
212 const prevG = previousData[idx + 1];
213 const prevB = previousData[idx + 2];
214 const diff =
215 Math.abs(r - prevR) + Math.abs(g - prevG) + Math.abs(b - prevB);
216 motion = Math.min(1, diff / 255 / motionSensitivity);
217 }
218
219 // Smooth motion
220 pixel.motion = pixel.motion * 0.7 + motion * 0.3;
221
222 // Set colors
223 let finalR = r;
224 let finalG = g;
225 let finalB = b;
226
227 if (colorMode === "monochrome") {
228 const brightness = (r + g + b) / 3 / 255;
229 finalR = Math.round(monoRGB.r * brightness);
230 finalG = Math.round(monoRGB.g * brightness);
231 finalB = Math.round(monoRGB.b * brightness);
232 }
233
234 // Apply invert
235 if (invertColors) {
236 finalR = 255 - finalR;
237 finalG = 255 - finalG;
238 finalB = 255 - finalB;
239 }
240
241 // Apply darken
242 if (darken > 0) {
243 const darkenFactor = 1 - darken;
244 finalR = Math.round(finalR * darkenFactor);
245 finalG = Math.round(finalG * darkenFactor);
246 finalB = Math.round(finalB * darkenFactor);
247 }
248
249 pixel.r = finalR;
250 pixel.g = finalG;
251 pixel.b = finalB;
252
253 // Set target elevation
254 pixel.targetElevation = pixel.motion * maxElevation;
255
256 // Smooth elevation transition
257 pixel.currentElevation +=
258 (pixel.targetElevation - pixel.currentElevation) * elevationSmoothing;
259 }
260 }
261
262 // Store current frame for next comparison
263 previousFrameRef.current = new Uint8ClampedArray(currentData);
264
265 // Render to display canvas
266 const dpr = window.devicePixelRatio || 1;
267 const displayWidth = displayCanvas.clientWidth;
268 const displayHeight = displayCanvas.clientHeight;
269
270 displayCanvas.width = displayWidth * dpr;
271 displayCanvas.height = displayHeight * dpr;
272 dispCtx.scale(dpr, dpr);
273
274 // Clear canvas
275 dispCtx.fillStyle = backgroundColor;
276 dispCtx.fillRect(0, 0, displayWidth, displayHeight);
277
278 // Calculate cell size (always square, cover entire container like object-fit: cover)
279 const cellSize = Math.max(
280 displayWidth / gridCols,
281 displayHeight / gridRows,
282 );
283 const gap = cellSize * gapRatio;
284
285 // Calculate offset to center the grid (negative offset for overflow, creating cover effect)
286 const gridWidth = cellSize * gridCols;
287 const gridHeight = cellSize * gridRows;
288 const offsetXGrid = (displayWidth - gridWidth) / 2;
289 const offsetYGrid = (displayHeight - gridHeight) / 2;
290
291 // Draw cells with 3D effect
292 for (let row = 0; row < gridRows; row++) {
293 for (let col = 0; col < gridCols; col++) {
294 const pixel = pixels[row]?.[col];
295 if (!pixel) continue;
296
297 const x = offsetXGrid + col * cellSize;
298 const y = offsetYGrid + row * cellSize;
299 const elevation = pixel.currentElevation;
300
301 // Calculate 3D offset (isometric-like projection) - MUCH larger effect
302 const offsetX = -elevation * 1.2;
303 const offsetY = -elevation * 1.8;
304
305 // Draw shadow - larger and more visible
306 if (elevation > 0.5) {
307 dispCtx.fillStyle = `rgba(0, 0, 0, ${Math.min(0.6, elevation * 0.04)})`;
308 dispCtx.fillRect(
309 x + gap / 2 + elevation * 1.5,
310 y + gap / 2 + elevation * 2.0,
311 cellSize - gap,
312 cellSize - gap,
313 );
314 }
315
316 // Draw side faces for 3D effect - thicker sides
317 if (elevation > 0.5) {
318 // Right side
319 dispCtx.fillStyle = `rgb(${Math.max(0, pixel.r - 80)}, ${Math.max(0, pixel.g - 80)}, ${Math.max(0, pixel.b - 80)})`;
320 dispCtx.beginPath();
321 dispCtx.moveTo(
322 x + cellSize - gap / 2 + offsetX,
323 y + gap / 2 + offsetY,
324 );
325 dispCtx.lineTo(x + cellSize - gap / 2, y + gap / 2);
326 dispCtx.lineTo(x + cellSize - gap / 2, y + cellSize - gap / 2);
327 dispCtx.lineTo(
328 x + cellSize - gap / 2 + offsetX,
329 y + cellSize - gap / 2 + offsetY,
330 );
331 dispCtx.closePath();
332 dispCtx.fill();
333
334 // Bottom side
335 dispCtx.fillStyle = `rgb(${Math.max(0, pixel.r - 50)}, ${Math.max(0, pixel.g - 50)}, ${Math.max(0, pixel.b - 50)})`;
336 dispCtx.beginPath();
337 dispCtx.moveTo(
338 x + gap / 2 + offsetX,
339 y + cellSize - gap / 2 + offsetY,
340 );
341 dispCtx.lineTo(x + gap / 2, y + cellSize - gap / 2);
342 dispCtx.lineTo(x + cellSize - gap / 2, y + cellSize - gap / 2);
343 dispCtx.lineTo(
344 x + cellSize - gap / 2 + offsetX,
345 y + cellSize - gap / 2 + offsetY,
346 );
347 dispCtx.closePath();
348 dispCtx.fill();
349 }
350
351 // Draw top face (main cell) - brighter when elevated
352 const brightness = 1 + elevation * 0.05;
353 dispCtx.fillStyle = `rgb(${Math.min(255, Math.round(pixel.r * brightness))}, ${Math.min(255, Math.round(pixel.g * brightness))}, ${Math.min(255, Math.round(pixel.b * brightness))})`;
354 dispCtx.fillRect(
355 x + gap / 2 + offsetX,
356 y + gap / 2 + offsetY,
357 cellSize - gap,
358 cellSize - gap,
359 );
360
361 // Draw light border around top face
362 dispCtx.strokeStyle = `rgba(${borderRGB.r}, ${borderRGB.g}, ${borderRGB.b}, ${borderOpacity + elevation * 0.008})`;
363 dispCtx.lineWidth = 0.5;
364 dispCtx.strokeRect(
365 x + gap / 2 + offsetX,
366 y + gap / 2 + offsetY,
367 cellSize - gap,
368 cellSize - gap,
369 );
370 }
371 }
372
373 animationRef.current = requestAnimationFrame(render);
374 }, [
375 gridCols,
376 gridRows,
377 mirror,
378 motionSensitivity,
379 colorMode,
380 monoRGB,
381 maxElevation,
382 elevationSmoothing,
383 backgroundColor,
384 gapRatio,
385 invertColors,
386 darken,
387 borderRGB,
388 borderOpacity,
389 ]);
390
391 // Start render loop when ready
392 useEffect(() => {
393 if (!isReady) return;
394
395 animationRef.current = requestAnimationFrame(render);
396
397 return () => {
398 cancelAnimationFrame(animationRef.current);
399 };
400 }, [isReady, render]);
401
402 return (
403 <div className={cn("relative h-full w-full", className)}>
404 {/* Hidden video element */}
405 <video
406 ref={videoRef}
407 className="pointer-events-none absolute h-0 w-0 opacity-0"
408 playsInline
409 muted
410 />
411
412 {/* Hidden processing canvas */}
413 <canvas
414 ref={processingCanvasRef}
415 className="pointer-events-none absolute h-0 w-0 opacity-0"
416 />
417
418 {/* Display canvas with fade-in */}
419 <canvas
420 ref={displayCanvasRef}
421 className={cn(
422 "h-full w-full transition-opacity duration-1000",
423 isReady ? "opacity-100" : "opacity-0",
424 )}
425 style={{ backgroundColor }}
426 />
427
428 {/* Error popup */}
429 {error && showErrorPopup && (
430 <div className="animate-in fade-in slide-in-from-top-2 fixed top-4 right-4 z-50 duration-300">
431 <div className="relative flex max-w-sm items-start gap-3 rounded-lg border border-white/10 bg-black/80 p-4 shadow-2xl backdrop-blur-xl">
432 {/* Close button */}
433 <button
434 onClick={() => setShowErrorPopup(false)}
435 className="absolute top-2 right-2 rounded-md p-1 text-white/40 transition-colors hover:bg-white/10 hover:text-white/70"
436 >
437 <svg
438 className="h-4 w-4"
439 fill="none"
440 viewBox="0 0 24 24"
441 stroke="currentColor"
442 >
443 <path
444 strokeLinecap="round"
445 strokeLinejoin="round"
446 strokeWidth={2}
447 d="M6 18L18 6M6 6l12 12"
448 />
449 </svg>
450 </button>
451
452 {/* Camera icon */}
453 <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-white/10">
454 <svg
455 className="h-5 w-5 text-white/60"
456 fill="none"
457 viewBox="0 0 24 24"
458 stroke="currentColor"
459 >
460 <path
461 strokeLinecap="round"
462 strokeLinejoin="round"
463 strokeWidth={1.5}
464 d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
465 />
466 </svg>
467 </div>
468
469 {/* Content */}
470 <div className="flex-1 pr-4">
471 <p className="text-sm font-medium text-white/90">
472 Camera access needed
473 </p>
474 <p className="mt-1 text-xs text-white/50">
475 Enable camera for the interactive background effect
476 </p>
477 <button
478 onClick={requestCameraAccess}
479 className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-white/10 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-white/20"
480 >
481 <svg
482 className="h-3.5 w-3.5"
483 fill="none"
484 viewBox="0 0 24 24"
485 stroke="currentColor"
486 >
487 <path
488 strokeLinecap="round"
489 strokeLinejoin="round"
490 strokeWidth={2}
491 d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
492 />
493 </svg>
494 Enable Camera
495 </button>
496 </div>
497 </div>
498 </div>
499 )}
500
501 {/* Minimized error indicator */}
502 {error && !showErrorPopup && (
503 <button
504 onClick={() => setShowErrorPopup(true)}
505 className="fixed top-4 right-4 z-50 flex h-10 w-10 items-center justify-center rounded-full border border-white/10 bg-black/60 text-white/50 shadow-lg backdrop-blur-xl transition-all hover:scale-105 hover:bg-black/80 hover:text-white/80"
506 title="Camera access required"
507 >
508 <svg
509 className="h-5 w-5"
510 fill="none"
511 viewBox="0 0 24 24"
512 stroke="currentColor"
513 >
514 <path
515 strokeLinecap="round"
516 strokeLinejoin="round"
517 strokeWidth={1.5}
518 d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
519 />
520 <path
521 strokeLinecap="round"
522 strokeLinejoin="round"
523 strokeWidth={2}
524 d="M3 3l18 18"
525 className="text-red-400"
526 stroke="currentColor"
527 />
528 </svg>
529 </button>
530 )}
531 </div>
532 );
533};
534
535export default WebcamPixelGrid;
536