A ascii-art component from Aceternity UI.
From Aceternity UI
1"use client";
2import React, {
3 useEffect,
4 useLayoutEffect,
5 useRef,
6 useState,
7 useCallback,
8 useId,
9} from "react";
10import { motion, useInView } from "motion/react";
11import { cn } from "@/lib/utils";
12
13const useIsomorphicLayoutEffect =
14 typeof window !== "undefined" ? useLayoutEffect : useEffect;
15
16const ASCII_CHARSETS = {
17 standard: " .,:;i1tfLCG08@",
18 blocks: " ░▒▓█",
19 binary: " 01",
20 dots: " ·•●",
21 minimal: " .:░▒",
22 dense: " .'`^\",:;Il!i><~+_-?][}{1)(|/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$",
23 arrows: " ←↑→↓↔↕↖↗↘↙",
24 stars: " ·✦✧★",
25 hash: " -=#",
26 pipes: " |/─\\│",
27 braille: " ⠁⠃⠇⠏⠟⠿⡿⣿",
28 circles: " ○◔◑◕●",
29 squares: " ▢▣▤▥▦▧▨▩",
30 hearts: " ♡♥",
31 math: " +-×÷=≠≈∞",
32} as const;
33
34type CharsetPreset = keyof typeof ASCII_CHARSETS;
35
36const isCharsetPreset = (value: string): value is CharsetPreset => {
37 return value in ASCII_CHARSETS;
38};
39
40const resolveCharset = (charset: string): string => {
41 if (isCharsetPreset(charset)) {
42 return ASCII_CHARSETS[charset];
43 }
44 return charset;
45};
46
47const resolveCssColor = (
48 color: string,
49 element: HTMLElement | null
50): string => {
51 if (!color) return color;
52
53 if (color.startsWith("var(")) {
54 if (!element) return "#ffffff";
55
56 const tempDiv = document.createElement("div");
57 tempDiv.style.color = color;
58 element.appendChild(tempDiv);
59 const computedColor = getComputedStyle(tempDiv).color;
60 element.removeChild(tempDiv);
61 return computedColor || "#ffffff";
62 }
63
64 return color;
65};
66
67type AsciiArtProps = {
68 src: string;
69 /** Number of ASCII columns (character resolution). Higher = more detail. */
70 resolution?: number;
71 /** Charset preset name ("standard", "blocks", "binary", etc.) or custom character string */
72 charset?: CharsetPreset | string;
73 /** Text color for the ASCII art (ignored if colored=true) */
74 color?: string;
75 /** Background color */
76 backgroundColor?: string;
77 /** Convert to inverted colors (dark bg, light text) */
78 inverted?: boolean;
79 /** Enable colored ASCII (uses image colors) */
80 colored?: boolean;
81 /** Enable animation on load */
82 animated?: boolean;
83 /** Animation style */
84 animationStyle?: "fade" | "typewriter" | "matrix" | "none";
85 /** Duration for fade animation in seconds */
86 animationDuration?: number;
87 /** Font family for ASCII characters */
88 fontFamily?: string;
89 /** Container className - use this to control size (e.g., w-full, h-64) */
90 className?: string;
91 /** Only animate when in view */
92 animateOnView?: boolean;
93 /** How the image should fit within the ASCII grid */
94 objectFit?: "cover" | "contain" | "fill";
95};
96const MATRIX_CHARSET = "ハミヒーウシナモニサワツオリアホテマケメエカキムユラセネスタヌヘ";
97
98type AsciiPixel = {
99 char: string;
100 r: number;
101 g: number;
102 b: number;
103};
104
105export const AsciiArt: React.FC<AsciiArtProps> = ({
106 src,
107 resolution = 80,
108 charset = "standard",
109 color = "#ffffff",
110 backgroundColor = "transparent",
111 inverted = false,
112 colored = false,
113 animated = true,
114 animationStyle = "fade",
115 animationDuration = 1,
116 fontFamily = "monospace",
117 className,
118 animateOnView = true,
119 objectFit = "cover",
120}) => {
121 const uniqueId = useId();
122 const [asciiData, setAsciiData] = useState<AsciiPixel[][]>([]);
123 const [isLoaded, setIsLoaded] = useState(false);
124 const [error, setError] = useState<string | null>(null);
125 const [hasAnimated, setHasAnimated] = useState(false);
126 const containerRef = useRef<HTMLDivElement>(null);
127 const canvasRef = useRef<HTMLCanvasElement>(null);
128 const animationRef = useRef<number | null>(null);
129 const isInView = useInView(containerRef, { once: true, amount: 0.1 });
130
131 const shouldStartAnimation = animated && animateOnView ? isInView : animated;
132 const shouldShowStatic = !animated || animationStyle === "none";
133
134 const resolvedCharset = resolveCharset(charset);
135 const effectiveCharset = inverted
136 ? resolvedCharset.split("").reverse().join("")
137 : resolvedCharset;
138
139 const defaultColor = inverted ? "#ffffff" : "#000000";
140 const textColor = color || defaultColor;
141
142 useEffect(() => {
143 let isCancelled = false;
144
145 const img = new Image();
146 img.crossOrigin = "anonymous";
147 img.src = src;
148
149 img.onload = () => {
150 if (isCancelled) return;
151
152 const canvas = document.createElement("canvas");
153 const ctx = canvas.getContext("2d");
154 if (!ctx) {
155 setError("Canvas context not available");
156 return;
157 }
158
159 const imgWidth = img.naturalWidth;
160 const imgHeight = img.naturalHeight;
161 const imgAspect = imgWidth / imgHeight;
162 const charAspectRatio = 0.55;
163
164 const cols = resolution;
165 const rows = Math.floor(cols * charAspectRatio);
166
167 canvas.width = cols;
168 canvas.height = rows;
169
170 const visualAspect = 1.0;
171
172 let sx = 0,
173 sy = 0,
174 sw = imgWidth,
175 sh = imgHeight;
176
177 if (objectFit === "cover") {
178 if (imgAspect > visualAspect) {
179 sw = imgHeight * visualAspect;
180 sx = (imgWidth - sw) / 2;
181 } else {
182 sh = imgWidth / visualAspect;
183 sy = (imgHeight - sh) / 2;
184 }
185 } else if (objectFit === "contain") {
186 ctx.fillStyle = "#000000";
187 ctx.fillRect(0, 0, cols, rows);
188
189 let dw, dh, dx, dy;
190 if (imgAspect > visualAspect) {
191 dw = cols;
192 dh = cols / imgAspect * charAspectRatio;
193 dx = 0;
194 dy = (rows - dh) / 2;
195 } else {
196 dh = rows;
197 dw = rows * imgAspect / charAspectRatio;
198 dx = (cols - dw) / 2;
199 dy = 0;
200 }
201 ctx.drawImage(img, dx, dy, dw, dh);
202 }
203
204 if (objectFit !== "contain") {
205 ctx.drawImage(img, sx, sy, sw, sh, 0, 0, cols, rows);
206 }
207
208 let imageData: ImageData;
209 try {
210 imageData = ctx.getImageData(0, 0, cols, rows);
211 } catch {
212 setError("Unable to read image data (CORS issue)");
213 return;
214 }
215
216 const data = imageData.data;
217 const result: AsciiPixel[][] = [];
218
219 for (let y = 0; y < rows; y++) {
220 const row: AsciiPixel[] = [];
221 for (let x = 0; x < cols; x++) {
222 const idx = (y * cols + x) * 4;
223 const r = data[idx];
224 const g = data[idx + 1];
225 const b = data[idx + 2];
226 const a = data[idx + 3];
227
228 const brightness = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
229 const adjustedBrightness = a === 0 ? 0 : brightness;
230
231 const charIndex = Math.floor(
232 adjustedBrightness * (effectiveCharset.length - 1)
233 );
234 const char = effectiveCharset[charIndex] || " ";
235
236 row.push({ char, r, g, b });
237 }
238 result.push(row);
239 }
240
241 setAsciiData(result);
242 setIsLoaded(true);
243 };
244
245 img.onerror = () => {
246 if (isCancelled) return;
247 setError("Failed to load image");
248 };
249
250 return () => {
251 isCancelled = true;
252 };
253 }, [src, resolution, effectiveCharset, objectFit]);
254
255 const drawCanvas = useCallback(
256 (progress: number = 1, matrixProgress?: number) => {
257 const canvas = canvasRef.current;
258 const container = containerRef.current;
259 if (!canvas || !container || asciiData.length === 0) return;
260
261 const ctx = canvas.getContext("2d");
262 if (!ctx) return;
263
264 const dpr = window.devicePixelRatio || 1;
265 const containerWidth = container.clientWidth;
266 const containerHeight = container.clientHeight;
267
268 if (containerWidth === 0 || containerHeight === 0) return;
269
270 canvas.width = containerWidth * dpr;
271 canvas.height = containerHeight * dpr;
272 canvas.style.width = `${containerWidth}px`;
273 canvas.style.height = `${containerHeight}px`;
274 ctx.scale(dpr, dpr);
275
276 const resolvedBgColor = resolveCssColor(backgroundColor, container);
277 const resolvedTextColor = resolveCssColor(textColor, container);
278
279 if (resolvedBgColor !== "transparent") {
280 ctx.fillStyle = resolvedBgColor;
281 ctx.fillRect(0, 0, containerWidth, containerHeight);
282 } else {
283 ctx.clearRect(0, 0, containerWidth, containerHeight);
284 }
285
286 const rows = asciiData.length;
287 const cols = asciiData[0]?.length || 0;
288 if (cols === 0) return;
289
290 const charWidth = containerWidth / cols;
291 const charHeight = containerHeight / rows;
292 const fontSize = Math.min(charWidth * 1.8, charHeight * 1.2);
293
294 ctx.font = `${fontSize}px ${fontFamily}`;
295 ctx.textBaseline = "top";
296 ctx.textAlign = "center";
297
298 const totalChars = rows * cols;
299 const revealedChars = Math.floor(progress * totalChars);
300
301 let charIndex = 0;
302 for (let y = 0; y < rows; y++) {
303 for (let x = 0; x < cols; x++) {
304 const pixel = asciiData[y][x];
305 const cx = x * charWidth + charWidth / 2;
306 const cy = y * charHeight;
307
308 if (animationStyle === "typewriter" && charIndex >= revealedChars) {
309 charIndex++;
310 continue;
311 }
312
313 let displayChar = pixel.char;
314 let displayColor = colored
315 ? `rgb(${pixel.r}, ${pixel.g}, ${pixel.b})`
316 : resolvedTextColor;
317
318 if (animationStyle === "matrix" && matrixProgress !== undefined) {
319 const charProgress = (x * 0.02 + y * 0.01) / 2;
320 if (matrixProgress < charProgress) {
321 charIndex++;
322 continue;
323 } else if (matrixProgress < charProgress + 0.15) {
324 displayChar =
325 MATRIX_CHARSET[
326 Math.floor(Math.random() * MATRIX_CHARSET.length)
327 ];
328 displayColor = "#00ff00";
329 ctx.shadowColor = "#00ff00";
330 ctx.shadowBlur = 5;
331 } else {
332 ctx.shadowBlur = 0;
333 }
334 }
335
336 ctx.fillStyle = displayColor;
337 ctx.globalAlpha = animationStyle === "fade" ? progress : 1;
338 ctx.fillText(displayChar, cx, cy);
339
340 charIndex++;
341 }
342 }
343
344 ctx.globalAlpha = 1;
345 ctx.shadowBlur = 0;
346 },
347 [
348 asciiData,
349 backgroundColor,
350 colored,
351 textColor,
352 fontFamily,
353 animationStyle,
354 ]
355 );
356
357 useEffect(() => {
358 if (!isLoaded || asciiData.length === 0) return;
359
360 const draw = () => {
361 const canvas = canvasRef.current;
362 const container = containerRef.current;
363 if (!canvas || !container) {
364 requestAnimationFrame(draw);
365 return;
366 }
367
368 if (shouldShowStatic || hasAnimated || !shouldStartAnimation) {
369 drawCanvas(1);
370 return;
371 }
372
373 const startTime = performance.now();
374 const duration =
375 animationStyle === "fade"
376 ? animationDuration * 1000
377 : animationStyle === "typewriter"
378 ? asciiData.length * asciiData[0]?.length * 2
379 : animationStyle === "matrix"
380 ? 3000
381 : 1000;
382
383 const animate = (currentTime: number) => {
384 const elapsed = currentTime - startTime;
385 const progress = Math.min(elapsed / duration, 1);
386
387 if (animationStyle === "matrix") {
388 drawCanvas(1, progress);
389 } else {
390 drawCanvas(progress);
391 }
392
393 if (progress < 1) {
394 animationRef.current = requestAnimationFrame(animate);
395 } else {
396 setHasAnimated(true);
397 }
398 };
399
400 animationRef.current = requestAnimationFrame(animate);
401 };
402
403 const frameId = requestAnimationFrame(draw);
404
405 return () => {
406 cancelAnimationFrame(frameId);
407 if (animationRef.current) {
408 cancelAnimationFrame(animationRef.current);
409 }
410 };
411 }, [
412 isLoaded,
413 shouldStartAnimation,
414 shouldShowStatic,
415 hasAnimated,
416 animationStyle,
417 animationDuration,
418 drawCanvas,
419 asciiData,
420 ]);
421
422 useIsomorphicLayoutEffect(() => {
423 if (!isLoaded || asciiData.length === 0) return;
424
425 const container = containerRef.current;
426 const canvas = canvasRef.current;
427 if (!container || !canvas) return;
428
429 drawCanvas(1);
430 }, [isLoaded, asciiData, drawCanvas]);
431
432 useEffect(() => {
433 if (!isLoaded || asciiData.length === 0) return;
434
435 const container = containerRef.current;
436 if (!container) return;
437
438 const resizeObserver = new ResizeObserver(() => {
439 drawCanvas(1);
440 });
441
442 resizeObserver.observe(container);
443
444 return () => resizeObserver.disconnect();
445 }, [isLoaded, asciiData, drawCanvas]);
446
447 if (error) {
448 return (
449 <div
450 className={cn(
451 "flex items-center justify-center text-red-500 text-sm font-mono",
452 className
453 )}
454 >
455 Error: {error}
456 </div>
457 );
458 }
459
460 if (!isLoaded) {
461 return (
462 <div
463 className={cn(
464 "flex items-center justify-center text-neutral-500 text-sm font-mono animate-pulse",
465 className
466 )}
467 style={{ backgroundColor }}
468 >
469 Loading...
470 </div>
471 );
472 }
473
474 const canvasElement = (
475 <canvas
476 key={uniqueId}
477 id={`ascii-canvas-${uniqueId}`}
478 ref={canvasRef}
479 className="block w-full h-full"
480 aria-label="ASCII art rendering of image"
481 role="img"
482 />
483 );
484
485 if (animationStyle === "fade" && animated && !hasAnimated) {
486 return (
487 <motion.div
488 ref={containerRef}
489 className={cn("overflow-hidden", className)}
490 style={{ backgroundColor }}
491 initial={{ opacity: 0 }}
492 animate={shouldStartAnimation ? { opacity: 1 } : { opacity: 0 }}
493 transition={{ duration: animationDuration * 0.3 }}
494 >
495 {canvasElement}
496 </motion.div>
497 );
498 }
499
500 return (
501 <div
502 ref={containerRef}
503 className={cn("overflow-hidden", className)}
504 style={{ backgroundColor }}
505 >
506 {canvasElement}
507 </div>
508 );
509};
510
511export const AsciiArtStatic: React.FC<
512 Omit<AsciiArtProps, "animated" | "animationStyle">
513> = (props) => {
514 return <AsciiArt {...props} animated={false} animationStyle="none" />;
515};
516