A canvas-text component from Aceternity UI.
From Aceternity UI
1"use client";
2import { cn } from "@/lib/utils";
3import React, { useEffect, useRef, useState, useCallback } from "react";
4
5interface CanvasTextProps {
6 text: string;
7 className?: string;
8 backgroundClassName?: string;
9 colors?: string[];
10 animationDuration?: number;
11 lineWidth?: number;
12 lineGap?: number;
13 curveIntensity?: number;
14 overlay?: boolean;
15}
16
17function resolveColor(color: string): string {
18 if (color.startsWith("var(")) {
19 const varName = color.slice(4, -1).trim();
20 const resolved = getComputedStyle(document.documentElement)
21 .getPropertyValue(varName)
22 .trim();
23 return resolved || color;
24 }
25 return color;
26}
27
28export function CanvasText({
29 text,
30 className = "",
31 backgroundClassName = "bg-white dark:bg-neutral-950",
32 colors = ["#ff6b6b", "#4ecdc4", "#45b7d1", "#96ceb4", "#ffeaa7", "#dfe6e9"],
33 animationDuration = 5,
34 lineWidth = 1.5,
35 lineGap = 10,
36 curveIntensity = 60,
37 overlay = false,
38}: CanvasTextProps) {
39 const canvasRef = useRef<HTMLCanvasElement>(null);
40 const textRef = useRef<HTMLSpanElement>(null);
41 const bgRef = useRef<HTMLSpanElement>(null);
42 const animationRef = useRef<number>(0);
43 const startTimeRef = useRef<number>(0);
44 const [bgColor, setBgColor] = useState("#0a0a0a");
45 const [resolvedColors, setResolvedColors] = useState<string[]>([]);
46 const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
47 const [font, setFont] = useState("");
48
49 const updateColors = useCallback(() => {
50 if (bgRef.current) {
51 const computed = window.getComputedStyle(bgRef.current);
52 setBgColor(computed.backgroundColor);
53 }
54 const resolved = colors.map(resolveColor);
55 setResolvedColors(resolved);
56 }, [colors]);
57
58 useEffect(() => {
59 updateColors();
60
61 const observer = new MutationObserver(updateColors);
62 observer.observe(document.documentElement, {
63 attributes: true,
64 attributeFilter: ["class"],
65 });
66
67 return () => observer.disconnect();
68 }, [updateColors]);
69
70 useEffect(() => {
71 const textEl = textRef.current;
72 if (!textEl) return;
73
74 const updateDimensions = () => {
75 const rect = textEl.getBoundingClientRect();
76 const computed = window.getComputedStyle(textEl);
77 setDimensions({
78 width: Math.ceil(rect.width) || 400,
79 height: Math.ceil(rect.height) || 200,
80 });
81 setFont(
82 `${computed.fontWeight} ${computed.fontSize} ${computed.fontFamily}`,
83 );
84 };
85
86 updateDimensions();
87
88 const resizeObserver = new ResizeObserver(updateDimensions);
89 resizeObserver.observe(textEl);
90
91 return () => resizeObserver.disconnect();
92 }, [text, className]);
93
94 useEffect(() => {
95 const canvas = canvasRef.current;
96 if (
97 !canvas ||
98 resolvedColors.length === 0 ||
99 dimensions.width === 0 ||
100 !font
101 )
102 return;
103
104 const ctx = canvas.getContext("2d", { alpha: true });
105 if (!ctx) return;
106
107 const { width, height } = dimensions;
108 const dpr = window.devicePixelRatio || 1;
109
110 canvas.width = width * dpr;
111 canvas.height = height * dpr;
112
113 ctx.font = font;
114 const metrics = ctx.measureText(text);
115 const ascent = metrics.actualBoundingBoxAscent;
116 const descent = metrics.actualBoundingBoxDescent;
117 const baselineY = (height + ascent - descent) / 2;
118
119 const numLines = Math.floor(height / lineGap) + 10;
120 startTimeRef.current = performance.now();
121
122 const animate = (currentTime: number) => {
123 const elapsed = (currentTime - startTimeRef.current) / 1000;
124 const phase = (elapsed / animationDuration) * Math.PI * 2;
125
126 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
127 ctx.clearRect(0, 0, width, height);
128
129 ctx.globalCompositeOperation = "source-over";
130 ctx.font = font;
131 ctx.textBaseline = "alphabetic";
132 ctx.textAlign = "left";
133 ctx.fillStyle = "#000";
134 ctx.fillText(text, 0, baselineY);
135
136 ctx.globalCompositeOperation = "source-in";
137 ctx.fillStyle = bgColor;
138 ctx.fillRect(0, 0, width, height);
139
140 ctx.globalCompositeOperation = "source-atop";
141 for (let i = 0; i < numLines; i++) {
142 const y = i * lineGap;
143
144 const curve1 = Math.sin(phase) * curveIntensity;
145 const curve2 = Math.sin(phase + 0.5) * curveIntensity * 0.6;
146
147 const colorIndex = i % resolvedColors.length;
148 ctx.strokeStyle = resolvedColors[colorIndex];
149 ctx.lineWidth = lineWidth;
150
151 ctx.beginPath();
152 ctx.moveTo(0, y);
153 ctx.bezierCurveTo(
154 width * 0.33,
155 y + curve1,
156 width * 0.66,
157 y + curve2,
158 width,
159 y,
160 );
161 ctx.stroke();
162 }
163
164 animationRef.current = requestAnimationFrame(animate);
165 };
166
167 animationRef.current = requestAnimationFrame(animate);
168
169 return () => {
170 cancelAnimationFrame(animationRef.current);
171 };
172 }, [
173 text,
174 font,
175 bgColor,
176 resolvedColors,
177 animationDuration,
178 lineWidth,
179 lineGap,
180 curveIntensity,
181 dimensions,
182 ]);
183
184 return (
185 <span
186 className={cn(
187 "relative inline-block",
188 overlay && "absolute inset-0",
189 className,
190 )}
191 >
192 <span
193 ref={bgRef}
194 className={cn(
195 "pointer-events-none absolute h-0 w-0 opacity-0",
196 backgroundClassName,
197 )}
198 aria-hidden="true"
199 />
200 <span ref={textRef} className="invisible inline-block" aria-hidden="true">
201 {text}
202 </span>
203 <canvas
204 ref={canvasRef}
205 className="pointer-events-none absolute top-0 left-0"
206 style={{
207 width: dimensions.width || "auto",
208 height: dimensions.height || "auto",
209 }}
210 aria-label={text}
211 role="img"
212 />
213 </span>
214 );
215}
216