A pixelated-canvas component from Aceternity UI.
From Aceternity UI
1"use client";
2import React from "react";
3
4type PixelatedCanvasProps = {
5 src: string;
6 width?: number;
7 height?: number;
8 /** Size of each cell (in CSS pixels) used for sampling and spacing. */
9 cellSize?: number;
10 /** Dot size as a fraction of cell size (0..1). */
11 dotScale?: number;
12 /** Shape of the dot drawn for each sample. */
13 shape?: "circle" | "square";
14 /** Optional background color to clear the canvas with before drawing. */
15 backgroundColor?: string;
16 /** Convert to grayscale before drawing. */
17 grayscale?: boolean;
18 className?: string;
19 /** Redraw on window resize using the provided width/height. */
20 responsive?: boolean;
21 /** 0..1. Higher value removes more dots in low-contrast regions. */
22 dropoutStrength?: number;
23 /** Enable interactive mouse distortion animation. */
24 interactive?: boolean;
25 /** Max per-dot offset (px) due to distortion. */
26 distortionStrength?: number;
27 /** Radius (px) around pointer influencing distortion. */
28 distortionRadius?: number;
29 /** How pixels move near the pointer. */
30 distortionMode?: "repel" | "attract" | "swirl";
31 /** 0..1 smoothing factor for pointer follow. */
32 followSpeed?: number;
33 /** Average multiple samples per cell instead of single center sample. */
34 sampleAverage?: boolean;
35 /** Apply a color tint (e.g., "#0ea5e9" or "rgb(14,165,233)"). */
36 tintColor?: string;
37 /** 0..1 tint mix amount with original colors. */
38 tintStrength?: number;
39 /** Cap animation frame rate to improve perf on large canvases. */
40 maxFps?: number;
41 /** Object-fit behavior for the source image within the canvas. */
42 objectFit?: "cover" | "contain" | "fill" | "none";
43 /** Random motion amplitude for dots near the pointer. */
44 jitterStrength?: number;
45 /** Speed factor for the random motion. */
46 jitterSpeed?: number;
47 /** Smoothly fade the distortion when the pointer leaves. */
48 fadeOnLeave?: boolean;
49 /** 0..1 smoothing factor for leave fade. Higher = faster fade. */
50 fadeSpeed?: number;
51};
52
53export const PixelatedCanvas: React.FC<PixelatedCanvasProps> = ({
54 src,
55 width = 400,
56 height = 500,
57 cellSize = 3,
58 dotScale = 0.9,
59 shape = "square",
60 backgroundColor = "#000000",
61 grayscale = false,
62 className,
63 responsive = false,
64 dropoutStrength = 0.4,
65 interactive = true,
66 distortionStrength = 3,
67 distortionRadius = 80,
68 distortionMode = "swirl",
69 followSpeed = 0.2,
70 sampleAverage = true,
71 tintColor = "#FFFFFF",
72 tintStrength = 0.2,
73 maxFps = 60,
74 objectFit = "cover",
75 jitterStrength = 4,
76 jitterSpeed = 4,
77 fadeOnLeave = true,
78 fadeSpeed = 0.1,
79}) => {
80 const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
81 const samplesRef = React.useRef<
82 Array<{
83 x: number;
84 y: number;
85 r: number;
86 g: number;
87 b: number;
88 a: number;
89 drop: boolean;
90 seed: number;
91 }>
92 >([]);
93 const dimsRef = React.useRef<{
94 width: number;
95 height: number;
96 dot: number;
97 } | null>(null);
98 const targetMouseRef = React.useRef<{ x: number; y: number }>({
99 x: -9999,
100 y: -9999,
101 });
102 const animMouseRef = React.useRef<{ x: number; y: number }>({
103 x: -9999,
104 y: -9999,
105 });
106 const rafRef = React.useRef<number | null>(null);
107 const lastFrameRef = React.useRef<number>(0);
108 const pointerInsideRef = React.useRef<boolean>(false);
109 const activityRef = React.useRef<number>(0);
110 const activityTargetRef = React.useRef<number>(0);
111
112 React.useEffect(() => {
113 let isCancelled = false;
114 const canvas = canvasRef.current;
115 if (!canvas) return;
116
117 const img = new Image();
118 img.crossOrigin = "anonymous";
119 img.src = src;
120
121 const compute = () => {
122 if (!canvas) return;
123 const dpr =
124 typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
125
126 const displayWidth = width ?? img.naturalWidth;
127 const displayHeight = height ?? img.naturalHeight;
128
129 canvas.width = Math.max(1, Math.floor(displayWidth * dpr));
130 canvas.height = Math.max(1, Math.floor(displayHeight * dpr));
131 canvas.style.width = `${displayWidth}px`;
132 canvas.style.height = `${displayHeight}px`;
133
134 const ctx = canvas.getContext("2d");
135 if (!ctx) return;
136 ctx.resetTransform();
137 ctx.scale(dpr, dpr);
138
139 if (backgroundColor) {
140 ctx.fillStyle = backgroundColor;
141 ctx.fillRect(0, 0, displayWidth, displayHeight);
142 } else {
143 ctx.clearRect(0, 0, displayWidth, displayHeight);
144 }
145
146 const offscreen = document.createElement("canvas");
147 offscreen.width = Math.max(1, Math.floor(displayWidth));
148 offscreen.height = Math.max(1, Math.floor(displayHeight));
149 const off = offscreen.getContext("2d");
150 if (!off) return;
151
152 const iw = img.naturalWidth || displayWidth;
153 const ih = img.naturalHeight || displayHeight;
154 let dw = displayWidth;
155 let dh = displayHeight;
156 let dx = 0;
157 let dy = 0;
158 if (objectFit === "cover") {
159 const scale = Math.max(displayWidth / iw, displayHeight / ih);
160 dw = Math.ceil(iw * scale);
161 dh = Math.ceil(ih * scale);
162 dx = Math.floor((displayWidth - dw) / 2);
163 dy = Math.floor((displayHeight - dh) / 2);
164 } else if (objectFit === "contain") {
165 const scale = Math.min(displayWidth / iw, displayHeight / ih);
166 dw = Math.ceil(iw * scale);
167 dh = Math.ceil(ih * scale);
168 dx = Math.floor((displayWidth - dw) / 2);
169 dy = Math.floor((displayHeight - dh) / 2);
170 } else if (objectFit === "fill") {
171 dw = displayWidth;
172 dh = displayHeight;
173 } else {
174 dw = iw;
175 dh = ih;
176 dx = Math.floor((displayWidth - dw) / 2);
177 dy = Math.floor((displayHeight - dh) / 2);
178 }
179 off.drawImage(img, dx, dy, dw, dh);
180
181 let imageData: ImageData;
182 try {
183 imageData = off.getImageData(0, 0, offscreen.width, offscreen.height);
184 } catch {
185 ctx.drawImage(img, 0, 0, displayWidth, displayHeight);
186 return;
187 }
188
189 const data = imageData.data;
190 const stride = offscreen.width * 4;
191 const effectiveDotSize = Math.max(1, Math.floor(cellSize * dotScale));
192 dimsRef.current = {
193 width: displayWidth,
194 height: displayHeight,
195 dot: effectiveDotSize,
196 };
197
198 const luminanceAt = (px: number, py: number) => {
199 const ix = Math.max(0, Math.min(offscreen.width - 1, px));
200 const iy = Math.max(0, Math.min(offscreen.height - 1, py));
201 const i = iy * stride + ix * 4;
202 const rr = data[i];
203 const gg = data[i + 1];
204 const bb = data[i + 2];
205 return 0.2126 * rr + 0.7152 * gg + 0.0722 * bb;
206 };
207
208 const hash2D = (ix: number, iy: number) => {
209 const s = Math.sin(ix * 12.9898 + iy * 78.233) * 43758.5453123;
210 return s - Math.floor(s);
211 };
212
213 const samples: Array<{
214 x: number;
215 y: number;
216 r: number;
217 g: number;
218 b: number;
219 a: number;
220 drop: boolean;
221 seed: number;
222 }> = [];
223
224 let tintRGB: [number, number, number] | null = null;
225 if (tintColor && tintStrength > 0) {
226 const parse = (c: string): [number, number, number] | null => {
227 if (c.startsWith("#")) {
228 const hex = c.slice(1);
229 if (hex.length === 3) {
230 const r = parseInt(hex[0] + hex[0], 16);
231 const g = parseInt(hex[1] + hex[1], 16);
232 const b = parseInt(hex[2] + hex[2], 16);
233 return [r, g, b];
234 }
235 const r = parseInt(hex.slice(0, 2), 16);
236 const g = parseInt(hex.slice(2, 4), 16);
237 const b = parseInt(hex.slice(4, 6), 16);
238 return [r, g, b];
239 }
240 const m = c.match(/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/i);
241 if (m)
242 return [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)];
243 return null;
244 };
245 tintRGB = parse(tintColor) as any;
246 }
247
248 for (let y = 0; y < offscreen.height; y += cellSize) {
249 const cy = Math.min(offscreen.height - 1, y + Math.floor(cellSize / 2));
250 for (let x = 0; x < offscreen.width; x += cellSize) {
251 const cx = Math.min(
252 offscreen.width - 1,
253 x + Math.floor(cellSize / 2),
254 );
255 let r = 0;
256 let g = 0;
257 let b = 0;
258 let a = 0;
259 if (!sampleAverage) {
260 const idx = cy * stride + cx * 4;
261 r = data[idx];
262 g = data[idx + 1];
263 b = data[idx + 2];
264 a = data[idx + 3] / 255;
265 } else {
266 let count = 0;
267 for (let oy = -1; oy <= 1; oy++) {
268 for (let ox = -1; ox <= 1; ox++) {
269 const sx = Math.max(0, Math.min(offscreen.width - 1, cx + ox));
270 const sy = Math.max(0, Math.min(offscreen.height - 1, cy + oy));
271 const sIdx = sy * stride + sx * 4;
272 r += data[sIdx];
273 g += data[sIdx + 1];
274 b += data[sIdx + 2];
275 a += data[sIdx + 3] / 255;
276 count++;
277 }
278 }
279 r = Math.round(r / count);
280 g = Math.round(g / count);
281 b = Math.round(b / count);
282 a = a / count;
283 }
284
285 if (grayscale) {
286 const L = Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b);
287 r = L;
288 g = L;
289 b = L;
290 } else if (tintRGB && tintStrength > 0) {
291 const k = Math.max(0, Math.min(1, tintStrength));
292 r = Math.round(r * (1 - k) + tintRGB[0] * k);
293 g = Math.round(g * (1 - k) + tintRGB[1] * k);
294 b = Math.round(b * (1 - k) + tintRGB[2] * k);
295 }
296
297 const Lc = luminanceAt(cx, cy);
298 const Lx1 = luminanceAt(cx - 1, cy);
299 const Lx2 = luminanceAt(cx + 1, cy);
300 const Ly1 = luminanceAt(cx, cy - 1);
301 const Ly2 = luminanceAt(cx, cy + 1);
302 const grad =
303 Math.abs(Lx2 - Lx1) +
304 Math.abs(Ly2 - Ly1) +
305 Math.abs(Lc - (Lx1 + Lx2 + Ly1 + Ly2) / 4);
306 const gradientNorm = Math.max(0, Math.min(1, grad / 255));
307 const dropoutProb = Math.max(
308 0,
309 Math.min(1, (1 - gradientNorm) * dropoutStrength),
310 );
311 const drop = hash2D(cx, cy) < dropoutProb;
312 const seed = hash2D(cx, cy);
313
314 samples.push({ x, y, r, g, b, a, drop, seed });
315 }
316 }
317
318 samplesRef.current = samples;
319 };
320
321 img.onload = () => {
322 if (isCancelled) return;
323 compute();
324 const canvasEl = canvasRef.current;
325 if (!canvasEl) return;
326
327 if (!interactive) {
328 const ctx = canvasEl.getContext("2d");
329 const dims = dimsRef.current;
330 const samples = samplesRef.current;
331 if (!ctx || !dims || !samples) return;
332 if (backgroundColor) {
333 ctx.fillStyle = backgroundColor;
334 ctx.fillRect(0, 0, dims.width, dims.height);
335 } else {
336 ctx.clearRect(0, 0, dims.width, dims.height);
337 }
338 for (const s of samples) {
339 if (s.drop || s.a <= 0) continue;
340 ctx.globalAlpha = s.a;
341 ctx.fillStyle = `rgb(${s.r}, ${s.g}, ${s.b})`;
342 if (shape === "circle") {
343 const radius = dims.dot / 2;
344 ctx.beginPath();
345 ctx.arc(
346 s.x + cellSize / 2,
347 s.y + cellSize / 2,
348 radius,
349 0,
350 Math.PI * 2,
351 );
352 ctx.fill();
353 } else {
354 ctx.fillRect(
355 s.x + cellSize / 2 - dims.dot / 2,
356 s.y + cellSize / 2 - dims.dot / 2,
357 dims.dot,
358 dims.dot,
359 );
360 }
361 }
362 ctx.globalAlpha = 1;
363 return;
364 }
365
366 const onPointerMove = (e: PointerEvent) => {
367 const rect = canvasEl.getBoundingClientRect();
368 targetMouseRef.current.x = e.clientX - rect.left;
369 targetMouseRef.current.y = e.clientY - rect.top;
370 pointerInsideRef.current = true;
371 activityTargetRef.current = 1;
372 };
373 const onPointerEnter = () => {
374 pointerInsideRef.current = true;
375 activityTargetRef.current = 1;
376 };
377 const onPointerLeave = () => {
378 pointerInsideRef.current = false;
379 if (fadeOnLeave) {
380 activityTargetRef.current = 0;
381 } else {
382 targetMouseRef.current.x = -9999;
383 targetMouseRef.current.y = -9999;
384 }
385 };
386 canvasEl.addEventListener("pointermove", onPointerMove);
387 canvasEl.addEventListener("pointerenter", onPointerEnter);
388 canvasEl.addEventListener("pointerleave", onPointerLeave);
389
390 const animate = () => {
391 const now = performance.now();
392 const minDelta = 1000 / Math.max(1, maxFps);
393 if (now - lastFrameRef.current < minDelta) {
394 rafRef.current = requestAnimationFrame(animate);
395 return;
396 }
397 lastFrameRef.current = now;
398 const ctx = canvasEl.getContext("2d");
399 const dims = dimsRef.current;
400 const samples = samplesRef.current;
401 if (!ctx || !dims || !samples) {
402 rafRef.current = requestAnimationFrame(animate);
403 return;
404 }
405
406 animMouseRef.current.x =
407 animMouseRef.current.x +
408 (targetMouseRef.current.x - animMouseRef.current.x) * followSpeed;
409 animMouseRef.current.y =
410 animMouseRef.current.y +
411 (targetMouseRef.current.y - animMouseRef.current.y) * followSpeed;
412
413 if (fadeOnLeave) {
414 activityRef.current =
415 activityRef.current +
416 (activityTargetRef.current - activityRef.current) * fadeSpeed;
417 } else {
418 activityRef.current = pointerInsideRef.current ? 1 : 0;
419 }
420
421 if (backgroundColor) {
422 ctx.fillStyle = backgroundColor;
423 ctx.fillRect(0, 0, dims.width, dims.height);
424 } else {
425 ctx.clearRect(0, 0, dims.width, dims.height);
426 }
427
428 const mx = animMouseRef.current.x;
429 const my = animMouseRef.current.y;
430 const sigma = Math.max(1, distortionRadius * 0.5);
431 const t = now * 0.001 * jitterSpeed;
432 const activity = Math.max(0, Math.min(1, activityRef.current));
433
434 for (const s of samples) {
435 if (s.drop || s.a <= 0) continue;
436 let drawX = s.x + cellSize / 2;
437 let drawY = s.y + cellSize / 2;
438 const dx = drawX - mx;
439 const dy = drawY - my;
440 const dist2 = dx * dx + dy * dy;
441 const falloff = Math.exp(-dist2 / (2 * sigma * sigma));
442 const influence = falloff * activity;
443 if (influence > 0.0005) {
444 if (distortionMode === "repel") {
445 const dist = Math.sqrt(dist2) + 0.0001;
446 drawX += (dx / dist) * distortionStrength * influence;
447 drawY += (dy / dist) * distortionStrength * influence;
448 } else if (distortionMode === "attract") {
449 const dist = Math.sqrt(dist2) + 0.0001;
450 drawX -= (dx / dist) * distortionStrength * influence;
451 drawY -= (dy / dist) * distortionStrength * influence;
452 } else if (distortionMode === "swirl") {
453 const angle = distortionStrength * 0.05 * influence;
454 const cosA = Math.cos(angle);
455 const sinA = Math.sin(angle);
456 const rx = cosA * dx - sinA * dy;
457 const ry = sinA * dx + cosA * dy;
458 drawX = mx + rx;
459 drawY = my + ry;
460 }
461
462 if (jitterStrength > 0) {
463 const k = s.seed * 43758.5453;
464 const jx = Math.sin(t + k) * jitterStrength * influence;
465 const jy = Math.cos(t + k * 1.13) * jitterStrength * influence;
466 drawX += jx;
467 drawY += jy;
468 }
469 }
470
471 ctx.globalAlpha = s.a;
472 ctx.fillStyle = `rgb(${s.r}, ${s.g}, ${s.b})`;
473 if (shape === "circle") {
474 const radius = dims.dot / 2;
475 ctx.beginPath();
476 ctx.arc(drawX, drawY, radius, 0, Math.PI * 2);
477 ctx.fill();
478 } else {
479 ctx.fillRect(
480 drawX - dims.dot / 2,
481 drawY - dims.dot / 2,
482 dims.dot,
483 dims.dot,
484 );
485 }
486 }
487 ctx.globalAlpha = 1;
488
489 rafRef.current = requestAnimationFrame(animate);
490 };
491
492 if (rafRef.current) cancelAnimationFrame(rafRef.current);
493 rafRef.current = requestAnimationFrame(animate);
494
495 const cleanup = () => {
496 canvasEl.removeEventListener("pointermove", onPointerMove);
497 canvasEl.removeEventListener("pointerenter", onPointerEnter);
498 canvasEl.removeEventListener("pointerleave", onPointerLeave);
499 if (rafRef.current) cancelAnimationFrame(rafRef.current);
500 };
501 (img as any)._cleanup = cleanup;
502 };
503
504 img.onerror = () => {
505 console.error("Failed to load image for PixelatedCanvas:", src);
506 };
507
508 if (responsive) {
509 const onResize = () => {
510 if (img.complete && img.naturalWidth) {
511 compute();
512 }
513 };
514 window.addEventListener("resize", onResize);
515 return () => {
516 isCancelled = true;
517 window.removeEventListener("resize", onResize);
518 if ((img as any)._cleanup) (img as any)._cleanup();
519 };
520 }
521
522 return () => {
523 isCancelled = true;
524 if ((img as any)._cleanup) (img as any)._cleanup();
525 };
526 }, [
527 src,
528 width,
529 height,
530 cellSize,
531 dotScale,
532 shape,
533 backgroundColor,
534 grayscale,
535 responsive,
536 dropoutStrength,
537 interactive,
538 distortionStrength,
539 distortionRadius,
540 distortionMode,
541 followSpeed,
542 sampleAverage,
543 tintColor,
544 tintStrength,
545 maxFps,
546 objectFit,
547 jitterStrength,
548 jitterSpeed,
549 fadeOnLeave,
550 fadeSpeed,
551 ]);
552
553 return (
554 <canvas
555 ref={canvasRef}
556 className={className}
557 aria-label="Pixelated rendering of source image"
558 role="img"
559 />
560 );
561};
562