1"use client"
2
3import React, {
4 useEffect,
5 useRef,
6 useState,
7 type ComponentPropsWithoutRef,
8} from "react"
9
10import { cn } from "@/lib/utils"
11
12interface MousePosition {
13 x: number
14 y: number
15}
16
17function MousePosition(): MousePosition {
18 const [mousePosition, setMousePosition] = useState<MousePosition>({
19 x: 0,
20 y: 0,
21 })
22
23 useEffect(() => {
24 const handleMouseMove = (event: MouseEvent) => {
25 setMousePosition({ x: event.clientX, y: event.clientY })
26 }
27
28 window.addEventListener("mousemove", handleMouseMove)
29
30 return () => {
31 window.removeEventListener("mousemove", handleMouseMove)
32 }
33 }, [])
34
35 return mousePosition
36}
37
38interface ParticlesProps extends ComponentPropsWithoutRef<"div"> {
39 className?: string
40 quantity?: number
41 staticity?: number
42 ease?: number
43 size?: number
44 refresh?: boolean
45 color?: string
46 vx?: number
47 vy?: number
48}
49
50function hexToRgb(hex: string): number[] {
51 hex = hex.replace("#", "")
52
53 if (hex.length === 3) {
54 hex = hex
55 .split("")
56 .map((char) => char + char)
57 .join("")
58 }
59
60 const hexInt = parseInt(hex, 16)
61 const red = (hexInt >> 16) & 255
62 const green = (hexInt >> 8) & 255
63 const blue = hexInt & 255
64 return [red, green, blue]
65}
66
67type Circle = {
68 x: number
69 y: number
70 translateX: number
71 translateY: number
72 size: number
73 alpha: number
74 targetAlpha: number
75 dx: number
76 dy: number
77 magnetism: number
78}
79
80export const Particles: React.FC<ParticlesProps> = ({
81 className = "",
82 quantity = 100,
83 staticity = 50,
84 ease = 50,
85 size = 0.4,
86 refresh = false,
87 color = "#ffffff",
88 vx = 0,
89 vy = 0,
90 ...props
91}) => {
92 const canvasRef = useRef<HTMLCanvasElement>(null)
93 const canvasContainerRef = useRef<HTMLDivElement>(null)
94 const context = useRef<CanvasRenderingContext2D | null>(null)
95 const circles = useRef<Circle[]>([])
96 const mousePosition = MousePosition()
97 const mouse = useRef<{ x: number; y: number }>({ x: 0, y: 0 })
98 const canvasSize = useRef<{ w: number; h: number }>({ w: 0, h: 0 })
99 const dpr = typeof window !== "undefined" ? window.devicePixelRatio : 1
100 const rafID = useRef<number | null>(null)
101 const resizeTimeout = useRef<NodeJS.Timeout | null>(null)
102 const initCanvasRef = useRef<() => void>(() => {})
103 const onMouseMoveRef = useRef<() => void>(() => {})
104 const animateRef = useRef<() => void>(() => {})
105
106 useEffect(() => {
107 if (canvasRef.current) {
108 context.current = canvasRef.current.getContext("2d")
109 }
110 initCanvasRef.current()
111 animateRef.current()
112
113 const handleResize = () => {
114 if (resizeTimeout.current) {
115 clearTimeout(resizeTimeout.current)
116 }
117 resizeTimeout.current = setTimeout(() => {
118 initCanvasRef.current()
119 }, 200)
120 }
121
122 window.addEventListener("resize", handleResize)
123
124 return () => {
125 if (rafID.current != null) {
126 window.cancelAnimationFrame(rafID.current)
127 }
128 if (resizeTimeout.current) {
129 clearTimeout(resizeTimeout.current)
130 }
131 window.removeEventListener("resize", handleResize)
132 }
133 }, [color])
134
135 useEffect(() => {
136 onMouseMoveRef.current()
137 }, [mousePosition.x, mousePosition.y])
138
139 useEffect(() => {
140 initCanvasRef.current()
141 }, [refresh])
142
143 const initCanvas = () => {
144 resizeCanvas()
145 drawParticles()
146 }
147
148 const onMouseMove = () => {
149 if (canvasRef.current) {
150 const rect = canvasRef.current.getBoundingClientRect()
151 const { w, h } = canvasSize.current
152 const x = mousePosition.x - rect.left - w / 2
153 const y = mousePosition.y - rect.top - h / 2
154 const inside = x < w / 2 && x > -w / 2 && y < h / 2 && y > -h / 2
155 if (inside) {
156 mouse.current.x = x
157 mouse.current.y = y
158 }
159 }
160 }
161
162 const resizeCanvas = () => {
163 if (canvasContainerRef.current && canvasRef.current && context.current) {
164 canvasSize.current.w = canvasContainerRef.current.offsetWidth
165 canvasSize.current.h = canvasContainerRef.current.offsetHeight
166
167 canvasRef.current.width = canvasSize.current.w * dpr
168 canvasRef.current.height = canvasSize.current.h * dpr
169 canvasRef.current.style.width = `${canvasSize.current.w}px`
170 canvasRef.current.style.height = `${canvasSize.current.h}px`
171 context.current.scale(dpr, dpr)
172
173 // Clear existing particles and create new ones with exact quantity
174 circles.current = []
175 for (let i = 0; i < quantity; i++) {
176 const circle = circleParams()
177 drawCircle(circle)
178 }
179 }
180 }
181
182 const circleParams = (): Circle => {
183 const x = Math.floor(Math.random() * canvasSize.current.w)
184 const y = Math.floor(Math.random() * canvasSize.current.h)
185 const translateX = 0
186 const translateY = 0
187 const pSize = Math.floor(Math.random() * 2) + size
188 const alpha = 0
189 const targetAlpha = parseFloat((Math.random() * 0.6 + 0.1).toFixed(1))
190 const dx = (Math.random() - 0.5) * 0.1
191 const dy = (Math.random() - 0.5) * 0.1
192 const magnetism = 0.1 + Math.random() * 4
193 return {
194 x,
195 y,
196 translateX,
197 translateY,
198 size: pSize,
199 alpha,
200 targetAlpha,
201 dx,
202 dy,
203 magnetism,
204 }
205 }
206
207 const rgb = hexToRgb(color)
208
209 const drawCircle = (circle: Circle, update = false) => {
210 if (context.current) {
211 const { x, y, translateX, translateY, size, alpha } = circle
212 context.current.translate(translateX, translateY)
213 context.current.beginPath()
214 context.current.arc(x, y, size, 0, 2 * Math.PI)
215 context.current.fillStyle = `rgba(${rgb.join(", ")}, ${alpha})`
216 context.current.fill()
217 context.current.setTransform(dpr, 0, 0, dpr, 0, 0)
218
219 if (!update) {
220 circles.current.push(circle)
221 }
222 }
223 }
224
225 const clearContext = () => {
226 if (context.current) {
227 context.current.clearRect(
228 0,
229 0,
230 canvasSize.current.w,
231 canvasSize.current.h
232 )
233 }
234 }
235
236 const drawParticles = () => {
237 clearContext()
238 const particleCount = quantity
239 for (let i = 0; i < particleCount; i++) {
240 const circle = circleParams()
241 drawCircle(circle)
242 }
243 }
244
245 const remapValue = (
246 value: number,
247 start1: number,
248 end1: number,
249 start2: number,
250 end2: number
251 ): number => {
252 const remapped =
253 ((value - start1) * (end2 - start2)) / (end1 - start1) + start2
254 return remapped > 0 ? remapped : 0
255 }
256
257 const animate = () => {
258 clearContext()
259 circles.current.forEach((circle: Circle, i: number) => {
260 // Handle the alpha value
261 const edge = [
262 circle.x + circle.translateX - circle.size, // distance from left edge
263 canvasSize.current.w - circle.x - circle.translateX - circle.size, // distance from right edge
264 circle.y + circle.translateY - circle.size, // distance from top edge
265 canvasSize.current.h - circle.y - circle.translateY - circle.size, // distance from bottom edge
266 ]
267 const closestEdge = edge.reduce((a, b) => Math.min(a, b))
268 const remapClosestEdge = parseFloat(
269 remapValue(closestEdge, 0, 20, 0, 1).toFixed(2)
270 )
271 if (remapClosestEdge > 1) {
272 circle.alpha += 0.02
273 if (circle.alpha > circle.targetAlpha) {
274 circle.alpha = circle.targetAlpha
275 }
276 } else {
277 circle.alpha = circle.targetAlpha * remapClosestEdge
278 }
279 circle.x += circle.dx + vx
280 circle.y += circle.dy + vy
281 circle.translateX +=
282 (mouse.current.x / (staticity / circle.magnetism) - circle.translateX) /
283 ease
284 circle.translateY +=
285 (mouse.current.y / (staticity / circle.magnetism) - circle.translateY) /
286 ease
287
288 drawCircle(circle, true)
289
290 // circle gets out of the canvas
291 if (
292 circle.x < -circle.size ||
293 circle.x > canvasSize.current.w + circle.size ||
294 circle.y < -circle.size ||
295 circle.y > canvasSize.current.h + circle.size
296 ) {
297 // remove the circle from the array
298 circles.current.splice(i, 1)
299 // create a new circle
300 const newCircle = circleParams()
301 drawCircle(newCircle)
302 }
303 })
304 rafID.current = window.requestAnimationFrame(animateRef.current)
305 }
306
307 initCanvasRef.current = initCanvas
308 onMouseMoveRef.current = onMouseMove
309 animateRef.current = animate
310
311 return (
312 <div
313 className={cn("pointer-events-none", className)}
314 ref={canvasContainerRef}
315 aria-hidden="true"
316 {...props}
317 >
318 <canvas ref={canvasRef} className="size-full" />
319 </div>
320 )
321}
322