A noise-background component from Aceternity UI.
From Aceternity UI
1"use client";
2
3import { cn } from "@/lib/utils";
4import {
5 motion,
6 useAnimationFrame,
7 useMotionTemplate,
8 useMotionValue,
9 useSpring,
10 useTransform,
11 MotionValue,
12} from "motion/react";
13import { useEffect, useRef } from "react";
14
15// Helper component for gradient layers
16function GradientLayer({
17 springX,
18 springY,
19 gradientColor,
20 opacity,
21 multiplier,
22}: {
23 springX: MotionValue<number>;
24 springY: MotionValue<number>;
25 gradientColor: string;
26 opacity: number;
27 multiplier: number;
28}) {
29 const x = useTransform(springX, (val) => val * multiplier);
30 const y = useTransform(springY, (val) => val * multiplier);
31 const background = useMotionTemplate`radial-gradient(circle at ${x}px ${y}px, ${gradientColor} 0%, transparent 50%)`;
32
33 return (
34 <motion.div
35 className="absolute inset-0"
36 style={{
37 opacity,
38 background,
39 }}
40 />
41 );
42}
43
44interface NoiseBackgroundProps {
45 children?: React.ReactNode;
46 className?: string;
47 containerClassName?: string;
48 gradientColors?: string[];
49 noiseIntensity?: number;
50 speed?: number;
51 backdropBlur?: boolean;
52 animating?: boolean;
53}
54
55export const NoiseBackground = ({
56 children,
57 className,
58 containerClassName,
59 gradientColors = [
60 "rgb(255, 100, 150)",
61 "rgb(100, 150, 255)",
62 "rgb(255, 200, 100)",
63 ],
64 noiseIntensity = 0.2,
65 speed = 0.1,
66 backdropBlur = false,
67 animating = true,
68}: NoiseBackgroundProps) => {
69 const containerRef = useRef<HTMLDivElement>(null);
70 const x = useMotionValue(0);
71 const y = useMotionValue(0);
72
73 // Use spring animation for smooth movement
74 const springX = useSpring(x, { stiffness: 100, damping: 30 });
75 const springY = useSpring(y, { stiffness: 100, damping: 30 });
76
77 // Transform for top gradient strip
78 const topGradientX = useTransform(springX, (val) => val * 0.1 - 50);
79
80 const velocityRef = useRef({ x: 0, y: 0 });
81 const lastDirectionChangeRef = useRef(0);
82
83 // Initialize position to center
84 useEffect(() => {
85 if (!containerRef.current) return;
86
87 const container = containerRef.current;
88 const rect = container.getBoundingClientRect();
89 const centerX = rect.width / 2;
90 const centerY = rect.height / 2;
91 x.set(centerX);
92 y.set(centerY);
93 }, [x, y]);
94
95 // Generate random velocity
96 const generateRandomVelocityRef = useRef(() => {
97 const angle = Math.random() * Math.PI * 2;
98 const magnitude = speed * (0.5 + Math.random() * 0.5); // Random speed between 0.5x and 1x
99 return {
100 x: Math.cos(angle) * magnitude,
101 y: Math.sin(angle) * magnitude,
102 };
103 });
104
105 // Update generateRandomVelocity when speed changes
106 useEffect(() => {
107 generateRandomVelocityRef.current = () => {
108 const angle = Math.random() * Math.PI * 2;
109 const magnitude = speed * (0.5 + Math.random() * 0.5);
110 return {
111 x: Math.cos(angle) * magnitude,
112 y: Math.sin(angle) * magnitude,
113 };
114 };
115 velocityRef.current = generateRandomVelocityRef.current();
116 }, [speed]);
117
118 // Animate using motion/react's useAnimationFrame
119 useAnimationFrame((time) => {
120 if (!animating || !containerRef.current) return;
121
122 const rect = containerRef.current.getBoundingClientRect();
123 const maxX = rect.width;
124 const maxY = rect.height;
125
126 // Change direction randomly every 1.5-3 seconds
127 if (time - lastDirectionChangeRef.current > 1500 + Math.random() * 1500) {
128 velocityRef.current = generateRandomVelocityRef.current();
129 lastDirectionChangeRef.current = time;
130 }
131
132 // Update position based on velocity (deltaTime is ~16ms per frame at 60fps)
133 const deltaTime = 16; // Approximate frame time
134 const currentX = x.get();
135 const currentY = y.get();
136
137 let newX = currentX + velocityRef.current.x * deltaTime;
138 let newY = currentY + velocityRef.current.y * deltaTime;
139
140 // When hitting edges, generate a completely new random direction
141 // This ensures truly random movement in all 360 degrees, not just horizontal/vertical
142 const padding = 20; // Keep some distance from edges
143
144 if (
145 newX < padding ||
146 newX > maxX - padding ||
147 newY < padding ||
148 newY > maxY - padding
149 ) {
150 // Generate completely random direction (full 360 degrees)
151 const angle = Math.random() * Math.PI * 2;
152 const magnitude = speed * (0.5 + Math.random() * 0.5);
153 velocityRef.current = {
154 x: Math.cos(angle) * magnitude,
155 y: Math.sin(angle) * magnitude,
156 };
157 // Reset timer to allow immediate new direction
158 lastDirectionChangeRef.current = time;
159 // Clamp position to stay within bounds
160 newX = Math.max(padding, Math.min(maxX - padding, newX));
161 newY = Math.max(padding, Math.min(maxY - padding, newY));
162 }
163
164 x.set(newX);
165 y.set(newY);
166 });
167
168 return (
169 <div
170 ref={containerRef}
171 className={cn(
172 "group relative overflow-hidden rounded-2xl bg-neutral-200 p-2 backdrop-blur-sm dark:bg-neutral-800",
173 "shadow-[0px_0.5px_1px_0px_var(--color-neutral-400)_inset,0px_1px_0px_0px_var(--color-neutral-100)]",
174 "dark:shadow-[0px_1px_0px_0px_var(--color-neutral-950)_inset,0px_1px_0px_0px_var(--color-neutral-800)]",
175 backdropBlur &&
176 "after:absolute after:inset-0 after:h-full after:w-full after:backdrop-blur-lg after:content-['']",
177 containerClassName,
178 )}
179 style={
180 {
181 "--noise-opacity": noiseIntensity,
182 } as React.CSSProperties
183 }
184 >
185 {/* Moving gradient layers */}
186 <GradientLayer
187 springX={springX}
188 springY={springY}
189 gradientColor={gradientColors[0]}
190 opacity={0.4}
191 multiplier={1}
192 />
193 <GradientLayer
194 springX={springX}
195 springY={springY}
196 gradientColor={gradientColors[1]}
197 opacity={0.3}
198 multiplier={0.7}
199 />
200 <GradientLayer
201 springX={springX}
202 springY={springY}
203 gradientColor={gradientColors[2] || gradientColors[0]}
204 opacity={0.25}
205 multiplier={1.2}
206 />
207
208 {/* Top gradient strip */}
209 <motion.div
210 className="absolute inset-x-0 top-0 h-1 rounded-t-2xl opacity-80 blur-sm"
211 style={{
212 background: `linear-gradient(to right, ${gradientColors.join(", ")})`,
213 x: animating ? topGradientX : 0,
214 }}
215 />
216
217 {/* Static Noise Pattern */}
218 <div className="pointer-events-none absolute inset-0 overflow-hidden">
219 <img
220 src="https://assets.aceternity.com/noise.webp"
221 alt=""
222 className="h-full w-full object-cover opacity-[var(--noise-opacity)]"
223 style={{ mixBlendMode: "overlay" }}
224 />
225 </div>
226
227 {/* Content */}
228 <div className={cn("relative z-10", className)}>{children}</div>
229 </div>
230 );
231};
232