diff --git a/registry/default/example/particles-demo.tsx b/registry/default/example/particles-demo.tsx index c65669acb..a35192de2 100644 --- a/registry/default/example/particles-demo.tsx +++ b/registry/default/example/particles-demo.tsx @@ -1,7 +1,7 @@ "use client"; -import { useEffect, useState } from "react"; import { useTheme } from "next-themes"; +import { useEffect, useState } from "react"; import Particles from "@/registry/default/magicui/particles"; @@ -15,11 +15,12 @@ export default function ParticlesDemo() { return (
- + Particles + q = ({ className = "", quantity = 100, @@ -77,6 +91,7 @@ const Particles: React.FC = ({ const canvasSize = useRef<{ w: number; h: number }>({ w: 0, h: 0 }); const dpr = typeof window !== "undefined" ? window.devicePixelRatio : 1; const rafID = useRef(null); + const resizeTimeout = useRef(); useEffect(() => { if (canvasRef.current) { @@ -84,13 +99,26 @@ const Particles: React.FC = ({ } initCanvas(); animate(); - window.addEventListener("resize", initCanvas); + + const handleResize = () => { + if (resizeTimeout.current) { + clearTimeout(resizeTimeout.current); + } + resizeTimeout.current = setTimeout(() => { + initCanvas(); + }, 200); + }; + + window.addEventListener("resize", handleResize); return () => { if (rafID.current != null) { window.cancelAnimationFrame(rafID.current); } - window.removeEventListener("resize", initCanvas); + if (resizeTimeout.current) { + clearTimeout(resizeTimeout.current); + } + window.removeEventListener("resize", handleResize); }; }, [color]); @@ -121,29 +149,23 @@ const Particles: React.FC = ({ } }; - type Circle = { - x: number; - y: number; - translateX: number; - translateY: number; - size: number; - alpha: number; - targetAlpha: number; - dx: number; - dy: number; - magnetism: number; - }; - const resizeCanvas = () => { if (canvasContainerRef.current && canvasRef.current && context.current) { - circles.current.length = 0; canvasSize.current.w = canvasContainerRef.current.offsetWidth; canvasSize.current.h = canvasContainerRef.current.offsetHeight; + canvasRef.current.width = canvasSize.current.w * dpr; canvasRef.current.height = canvasSize.current.h * dpr; canvasRef.current.style.width = `${canvasSize.current.w}px`; canvasRef.current.style.height = `${canvasSize.current.h}px`; context.current.scale(dpr, dpr); + + // Clear existing particles and create new ones with exact quantity + circles.current = []; + for (let i = 0; i < quantity; i++) { + const circle = circleParams(); + drawCircle(circle); + } } }; @@ -267,7 +289,6 @@ const Particles: React.FC = ({ // create a new circle const newCircle = circleParams(); drawCircle(newCircle); - // update the circle position } }); rafID.current = window.requestAnimationFrame(animate);