A dither-shader component from Aceternity UI.
From Aceternity UI
1"use client";
2import React, { useEffect, useRef, useCallback, useState } from "react";
3import { cn } from "@/lib/utils";
4
5type DitheringMode = "bayer" | "halftone" | "noise" | "crosshatch";
6type ColorMode = "original" | "grayscale" | "duotone" | "custom";
7
8interface DitherShaderProps {
9 /** Source image URL */
10 src: string;
11 /** Size of the dithering grid cells */
12 gridSize?: number;
13 /** Type of dithering pattern */
14 ditherMode?: DitheringMode;
15 /** Color processing mode */
16 colorMode?: ColorMode;
17 /** Invert the dithered output colors */
18 invert?: boolean;
19 /** Pixelation multiplier (1 = no pixelation, higher = more pixelated) */
20 pixelRatio?: number;
21 /** Primary color for duotone mode */
22 primaryColor?: string;
23 /** Secondary color for duotone mode */
24 secondaryColor?: string;
25 /** Custom color palette array for custom mode */
26 customPalette?: string[];
27 /** Brightness adjustment (-1 to 1) */
28 brightness?: number;
29 /** Contrast adjustment (0 to 2, 1 = normal) */
30 contrast?: number;
31 /** Background color behind the dithered image */
32 backgroundColor?: string;
33 /** Object fit behavior */
34 objectFit?: "cover" | "contain" | "fill" | "none";
35 /** Threshold bias for dithering (0 to 1) */
36 threshold?: number;
37 /** Enable animation effect */
38 animated?: boolean;
39 /** Animation speed (lower = slower) */
40 animationSpeed?: number;
41 /** Additional CSS classes for the container (use this to set size via Tailwind) */
42 className?: string;
43}
44
45// 4x4 Bayer matrix for ordered dithering
46const BAYER_MATRIX_4x4 = [
47 [0, 8, 2, 10],
48 [12, 4, 14, 6],
49 [3, 11, 1, 9],
50 [15, 7, 13, 5],
51];
52
53// 8x8 Bayer matrix for finer dithering
54const BAYER_MATRIX_8x8 = [
55 [0, 32, 8, 40, 2, 34, 10, 42],
56 [48, 16, 56, 24, 50, 18, 58, 26],
57 [12, 44, 4, 36, 14, 46, 6, 38],
58 [60, 28, 52, 20, 62, 30, 54, 22],
59 [3, 35, 11, 43, 1, 33, 9, 41],
60 [51, 19, 59, 27, 49, 17, 57, 25],
61 [15, 47, 7, 39, 13, 45, 5, 37],
62 [63, 31, 55, 23, 61, 29, 53, 21],
63];
64
65function parseColor(color: string): [number, number, number] {
66 if (color.startsWith("#")) {
67 const hex = color.slice(1);
68 if (hex.length === 3) {
69 return [
70 parseInt(hex[0] + hex[0], 16),
71 parseInt(hex[1] + hex[1], 16),
72 parseInt(hex[2] + hex[2], 16),
73 ];
74 }
75 return [
76 parseInt(hex.slice(0, 2), 16),
77 parseInt(hex.slice(2, 4), 16),
78 parseInt(hex.slice(4, 6), 16),
79 ];
80 }
81 const match = color.match(/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/i);
82 if (match) {
83 return [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])];
84 }
85 return [0, 0, 0];
86}
87
88function getLuminance(r: number, g: number, b: number): number {
89 return 0.299 * r + 0.587 * g + 0.114 * b;
90}
91
92function clamp(value: number, min: number, max: number): number {
93 return Math.max(min, Math.min(max, value));
94}
95
96export const DitherShader: React.FC<DitherShaderProps> = ({
97 src,
98 gridSize = 4,
99 ditherMode = "bayer",
100 colorMode = "original",
101 invert = false,
102 pixelRatio = 1,
103 primaryColor = "#000000",
104 secondaryColor = "#ffffff",
105 customPalette = ["#000000", "#ffffff"],
106 brightness = 0,
107 contrast = 1,
108 backgroundColor = "transparent",
109 objectFit = "cover",
110 threshold = 0.5,
111 animated = false,
112 animationSpeed = 0.02,
113 className,
114}) => {
115 const containerRef = useRef<HTMLDivElement>(null);
116 const canvasRef = useRef<HTMLCanvasElement>(null);
117 const animationRef = useRef<number | null>(null);
118 const timeRef = useRef<number>(0);
119 const imageRef = useRef<HTMLImageElement | null>(null);
120 const imageDataRef = useRef<ImageData | null>(null);
121 const dimensionsRef = useRef<{ width: number; height: number }>({
122 width: 0,
123 height: 0,
124 });
125
126 const [dimensions, setDimensions] = useState<{
127 width: number;
128 height: number;
129 }>({ width: 0, height: 0 });
130
131 const parsedPrimaryColor = parseColor(primaryColor);
132 const parsedSecondaryColor = parseColor(secondaryColor);
133 const parsedCustomPalette = customPalette.map(parseColor);
134
135 const applyDithering = useCallback(
136 (
137 ctx: CanvasRenderingContext2D,
138 displayWidth: number,
139 displayHeight: number,
140 time: number = 0,
141 ) => {
142 const canvas = canvasRef.current;
143 if (!canvas || !imageDataRef.current) return;
144
145 // Clear with background
146 if (backgroundColor !== "transparent") {
147 ctx.fillStyle = backgroundColor;
148 ctx.fillRect(0, 0, displayWidth, displayHeight);
149 } else {
150 ctx.clearRect(0, 0, displayWidth, displayHeight);
151 }
152
153 const sourceData = imageDataRef.current.data;
154 const sourceWidth = imageDataRef.current.width;
155 const sourceHeight = imageDataRef.current.height;
156
157 const effectivePixelSize = Math.max(1, Math.floor(gridSize * pixelRatio));
158 const matrixSize = gridSize <= 4 ? 4 : 8;
159 const bayerMatrix = gridSize <= 4 ? BAYER_MATRIX_4x4 : BAYER_MATRIX_8x8;
160 const matrixScale = matrixSize === 4 ? 16 : 64;
161
162 // Process pixels
163 for (let y = 0; y < displayHeight; y += effectivePixelSize) {
164 for (let x = 0; x < displayWidth; x += effectivePixelSize) {
165 // Map display coordinates to source image coordinates
166 const srcX = Math.floor((x / displayWidth) * sourceWidth);
167 const srcY = Math.floor((y / displayHeight) * sourceHeight);
168 const srcIdx = (srcY * sourceWidth + srcX) * 4;
169
170 let r = sourceData[srcIdx] || 0;
171 let g = sourceData[srcIdx + 1] || 0;
172 let b = sourceData[srcIdx + 2] || 0;
173 const a = sourceData[srcIdx + 3] || 0;
174
175 if (a < 10) continue; // Skip fully transparent pixels
176
177 // Apply brightness and contrast
178 r = clamp((r - 128) * contrast + 128 + brightness * 255, 0, 255);
179 g = clamp((g - 128) * contrast + 128 + brightness * 255, 0, 255);
180 b = clamp((b - 128) * contrast + 128 + brightness * 255, 0, 255);
181
182 // Calculate luminance
183 const luminance = getLuminance(r, g, b) / 255;
184
185 // Get dither threshold based on mode
186 let ditherThreshold: number;
187 const matrixX = Math.floor(x / gridSize) % matrixSize;
188 const matrixY = Math.floor(y / gridSize) % matrixSize;
189
190 switch (ditherMode) {
191 case "bayer":
192 ditherThreshold = bayerMatrix[matrixY][matrixX] / matrixScale;
193 break;
194 case "halftone": {
195 const angle = Math.PI / 4;
196 const scale = gridSize * 2;
197 const rotX = x * Math.cos(angle) + y * Math.sin(angle);
198 const rotY = -x * Math.sin(angle) + y * Math.cos(angle);
199 const pattern =
200 (Math.sin(rotX / scale) + Math.sin(rotY / scale) + 2) / 4;
201 ditherThreshold = pattern;
202 break;
203 }
204 case "noise": {
205 const noiseVal =
206 Math.sin(x * 12.9898 + y * 78.233 + time * 100) * 43758.5453;
207 ditherThreshold = noiseVal - Math.floor(noiseVal);
208 break;
209 }
210 case "crosshatch": {
211 const line1 = (x + y) % (gridSize * 2) < gridSize ? 1 : 0;
212 const line2 =
213 (x - y + gridSize * 4) % (gridSize * 2) < gridSize ? 1 : 0;
214 ditherThreshold = (line1 + line2) / 2;
215 break;
216 }
217 default:
218 ditherThreshold = bayerMatrix[matrixY][matrixX] / matrixScale;
219 }
220
221 // Adjust threshold with user setting
222 ditherThreshold = ditherThreshold * (1 - threshold) + threshold * 0.5;
223
224 // Determine output color based on color mode
225 let outputColor: [number, number, number];
226
227 switch (colorMode) {
228 case "grayscale": {
229 const shouldBeDark = luminance < ditherThreshold;
230 outputColor = shouldBeDark ? [0, 0, 0] : [255, 255, 255];
231 break;
232 }
233 case "duotone": {
234 const shouldBeDark = luminance < ditherThreshold;
235 outputColor = shouldBeDark
236 ? parsedPrimaryColor
237 : parsedSecondaryColor;
238 break;
239 }
240 case "custom": {
241 if (parsedCustomPalette.length === 2) {
242 const shouldBeDark = luminance < ditherThreshold;
243 outputColor = shouldBeDark
244 ? parsedCustomPalette[0]
245 : parsedCustomPalette[1];
246 } else {
247 // Quantize to closest palette color with dithering
248 const adjustedLuminance =
249 luminance + (ditherThreshold - 0.5) * 0.5;
250 const paletteIndex = Math.floor(
251 clamp(adjustedLuminance, 0, 1) *
252 (parsedCustomPalette.length - 1),
253 );
254 outputColor = parsedCustomPalette[paletteIndex];
255 }
256 break;
257 }
258 case "original":
259 default: {
260 // Apply dithering while preserving colors
261 const ditherAmount = ditherThreshold - 0.5;
262 const adjustedR = clamp(r + ditherAmount * 64, 0, 255);
263 const adjustedG = clamp(g + ditherAmount * 64, 0, 255);
264 const adjustedB = clamp(b + ditherAmount * 64, 0, 255);
265
266 // Quantize to fewer levels for dithered look
267 const levels = 4;
268 outputColor = [
269 Math.round(adjustedR / (255 / levels)) * (255 / levels),
270 Math.round(adjustedG / (255 / levels)) * (255 / levels),
271 Math.round(adjustedB / (255 / levels)) * (255 / levels),
272 ];
273 break;
274 }
275 }
276
277 // Apply inversion
278 if (invert) {
279 outputColor = [
280 255 - outputColor[0],
281 255 - outputColor[1],
282 255 - outputColor[2],
283 ];
284 }
285
286 // Draw the pixel
287 ctx.fillStyle = `rgb(${outputColor[0]}, ${outputColor[1]}, ${outputColor[2]})`;
288 ctx.fillRect(x, y, effectivePixelSize, effectivePixelSize);
289 }
290 }
291 },
292 [
293 gridSize,
294 ditherMode,
295 colorMode,
296 invert,
297 pixelRatio,
298 parsedPrimaryColor,
299 parsedSecondaryColor,
300 parsedCustomPalette,
301 brightness,
302 contrast,
303 backgroundColor,
304 threshold,
305 ],
306 );
307
308 // Setup resize observer for responsive sizing
309 useEffect(() => {
310 const container = containerRef.current;
311 if (!container) return;
312
313 const resizeObserver = new ResizeObserver((entries) => {
314 for (const entry of entries) {
315 const { width, height } = entry.contentRect;
316 if (width > 0 && height > 0) {
317 dimensionsRef.current = { width, height };
318 setDimensions({ width, height });
319 }
320 }
321 });
322
323 resizeObserver.observe(container);
324
325 return () => {
326 resizeObserver.disconnect();
327 };
328 }, []);
329
330 // Process image and apply dithering when dimensions or settings change
331 useEffect(() => {
332 const canvas = canvasRef.current;
333 if (!canvas || dimensions.width === 0 || dimensions.height === 0) return;
334
335 let isCancelled = false;
336
337 const processImage = (img: HTMLImageElement) => {
338 if (isCancelled) return;
339
340 const dpr =
341 typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
342 const displayWidth = dimensions.width;
343 const displayHeight = dimensions.height;
344
345 canvas.width = Math.floor(displayWidth * dpr);
346 canvas.height = Math.floor(displayHeight * dpr);
347
348 const ctx = canvas.getContext("2d");
349 if (!ctx) return;
350 ctx.resetTransform();
351 ctx.scale(dpr, dpr);
352
353 // Create offscreen canvas to get image data
354 const offscreen = document.createElement("canvas");
355 const iw = img.naturalWidth || displayWidth;
356 const ih = img.naturalHeight || displayHeight;
357
358 let dw = displayWidth;
359 let dh = displayHeight;
360 let dx = 0;
361 let dy = 0;
362
363 if (objectFit === "cover") {
364 const scale = Math.max(displayWidth / iw, displayHeight / ih);
365 dw = Math.ceil(iw * scale);
366 dh = Math.ceil(ih * scale);
367 dx = Math.floor((displayWidth - dw) / 2);
368 dy = Math.floor((displayHeight - dh) / 2);
369 } else if (objectFit === "contain") {
370 const scale = Math.min(displayWidth / iw, displayHeight / ih);
371 dw = Math.ceil(iw * scale);
372 dh = Math.ceil(ih * scale);
373 dx = Math.floor((displayWidth - dw) / 2);
374 dy = Math.floor((displayHeight - dh) / 2);
375 } else if (objectFit === "fill") {
376 dw = displayWidth;
377 dh = displayHeight;
378 } else {
379 dw = iw;
380 dh = ih;
381 dx = Math.floor((displayWidth - dw) / 2);
382 dy = Math.floor((displayHeight - dh) / 2);
383 }
384
385 offscreen.width = displayWidth;
386 offscreen.height = displayHeight;
387 const offCtx = offscreen.getContext("2d");
388 if (!offCtx) return;
389
390 offCtx.drawImage(img, dx, dy, dw, dh);
391
392 try {
393 imageDataRef.current = offCtx.getImageData(
394 0,
395 0,
396 displayWidth,
397 displayHeight,
398 );
399 } catch {
400 console.error("Could not get image data. CORS issue?");
401 return;
402 }
403
404 // Initial render
405 applyDithering(ctx, displayWidth, displayHeight, 0);
406
407 // Setup animation if enabled
408 if (animated) {
409 const animate = () => {
410 if (isCancelled) return;
411 timeRef.current += animationSpeed;
412 applyDithering(ctx, displayWidth, displayHeight, timeRef.current);
413 animationRef.current = requestAnimationFrame(animate);
414 };
415 animationRef.current = requestAnimationFrame(animate);
416 }
417 };
418
419 // If image is already loaded, reprocess it
420 if (imageRef.current && imageRef.current.complete) {
421 processImage(imageRef.current);
422 } else {
423 // Load the image
424 const img = new Image();
425 img.crossOrigin = "anonymous";
426 img.src = src;
427
428 img.onload = () => {
429 if (isCancelled) return;
430 imageRef.current = img;
431 processImage(img);
432 };
433
434 img.onerror = () => {
435 console.error("Failed to load image for DitherShader:", src);
436 };
437 }
438
439 return () => {
440 isCancelled = true;
441 if (animationRef.current) {
442 cancelAnimationFrame(animationRef.current);
443 }
444 };
445 }, [src, dimensions, objectFit, animated, animationSpeed, applyDithering]);
446
447 return (
448 <div ref={containerRef} className={cn("relative h-full w-full", className)}>
449 <canvas
450 ref={canvasRef}
451 className="absolute inset-0 h-full w-full"
452 style={{ imageRendering: "pixelated" }}
453 aria-label="Dithered image"
454 role="img"
455 />
456 </div>
457 );
458};
459
460export default DitherShader;
461