UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.
feat(floating-3d-particles): add canvas-based 3d particle background (#1002)
Miles7f2603022997
diff --git a/apps/www/config/docs.ts b/apps/www/config/docs.tsindex ddb7c84f..74405e34 100644--- a/apps/www/config/docs.ts+++ b/apps/www/config/docs.ts@@ -562,6 +562,12 @@ export const docsConfig: DocsConfig = {items: [],label: "New",},+ {+ title: "Floating 3D Particles",+ href: `/docs/components/floating-3d-particles`,+ items: [],+ label: "New",+ },],},{diff --git a/apps/www/content/docs/components/floating-3d-particles.mdx b/apps/www/content/docs/components/floating-3d-particles.mdxnew file mode 100644index 00000000..e0597313--- /dev/null+++ b/apps/www/content/docs/components/floating-3d-particles.mdx@@ -0,0 +1,76 @@+---+title: Floating 3D Particles+date: 2026-08-16+description: A canvas-based pseudo-3D particle field with perspective projection, continuous rotation, buoyant drift and depth-aware rendering.+author: Miles+published: true+---++<ComponentPreview name="floating-3d-particles-demo" />++## Installation++<Tabs defaultValue="cli">++<TabsList>+ <TabsTrigger value="cli">CLI</TabsTrigger>+ <TabsTrigger value="manual">Manual</TabsTrigger>+</TabsList>+<TabsContent value="cli">++```bash+npx shadcn@latest add @magicui/floating-3d-particles+```++</TabsContent>++<TabsContent value="manual">++<Steps>++<Step>Copy and paste the following code into your project.</Step>++<ComponentSource name="floating-3d-particles" />++<Step>Update the import paths to match your project setup.</Step>++</Steps>++</TabsContent>++</Tabs>++## Examples++### Plain Background++<ComponentPreview name="floating-3d-particles-demo-2" />++## Usage++`Floating3DParticles` renders an absolutely positioned `canvas` (`inset-0`, `pointer-events-none`). Place it inside a `relative` container and layer any foreground content above it with `z-10`.++```tsx showLineNumbers+import { Floating3DParticles } from "@/components/ui/floating-3d-particles"+```++```tsx showLineNumbers+<div className="relative flex h-[500px] w-full items-center justify-center overflow-hidden rounded-lg border">+ <Floating3DParticles color="#8B5CF6" quantity={400} />+ <div className="relative z-10 text-center">+ <h2 className="text-3xl font-bold">Build Something Magical</h2>+ </div>+</div>+```++## Props++| Prop | Type | Default | Description |+| ----------- | -------- | ----------- | --------------------------------------------------------------------------------------------------------- |+| `className` | `string` | `-` | Additional CSS classes for the canvas element. |+| `quantity` | `number` | `400` | Number of particles on desktop viewports. Automatically scales down to 20% on mobile screens (< 768px). |+| `color` | `string` | `"#8B5CF6"` | Particle color (supports 3-digit or 6-digit hex). |+| `size` | `number` | `5` | Mean particle radius in px. Each particle varies within ±40% of this value. |+| `opacity` | `number` | `0.3` | Mean particle opacity (0–1). Each particle varies within ±0.2, clamped to [0, 1]. |+| `drift` | `number` | `0.8` | Vertical floating speed in px per frame. Positive drifts upward, negative downward. |+| `depth` | `number` | `0.5` | 3D depth intensity (0–1). `0` = flat 2D plane; `1` = strong perspective with pronounced near/far scaling. |diff --git a/apps/www/public/llms-full.txt b/apps/www/public/llms-full.txtindex 8fa0f92c..7f8486e9 100644--- a/apps/www/public/llms-full.txt+++ b/apps/www/public/llms-full.txt@@ -8400,6 +8400,426 @@ export default function FlickeringGridRoundedDemo() {+===== COMPONENT: floating-3d-particles =====+Title: Floating 3D Particles+Description: A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.++--- file: magicui/floating-3d-particles.tsx ---+"use client"++import * as React from "react"++import { cn } from "@/lib/utils"++export interface Floating3DParticlesProps extends Omit<+ React.CanvasHTMLAttributes<HTMLCanvasElement>,+ "width" | "height"+> {+ /**+ * Number of particles rendered on desktop viewports.+ * On mobile screens (< 768px), particle count automatically scales down+ * to 20 % to preserve smooth frame rates.+ * @default 400+ */+ quantity?: number+ /**+ * Particle color — 3 or 6 digit hex string.+ * @default "#8B5CF6"+ */+ color?: string+ /**+ * Mean particle radius in px. Each particle is randomly assigned a size+ * within ±40 % of this value.+ * @default 5+ */+ size?: number+ /**+ * Mean particle opacity (0–1). Each particle randomly varies within+ * ±0.2 of this value, clamped to [0, 1].+ * @default 0.3+ */+ opacity?: number+ /**+ * Vertical floating speed in px per frame. Positive values drift upward,+ * negative values downward.+ * @default 0.8+ */+ drift?: number+ /**+ * 3-D depth intensity on a 0–1 scale. `0` produces a flat 2D plane; `1`+ * creates strong perspective with pronounced near/far scaling.+ * @default 0.5+ */+ depth?: number+}++// ---------------------------------------------------------------------------+// Particle State (Polar coordinates + 3D perspective projection)+// ---------------------------------------------------------------------------++interface Particle {+ angle: number+ radius: number+ y: number+ size: number+ angularSpeed: number+ opacity: number+ screenX: number+ screenY: number+ projectedScale: number+}++// ---------------------------------------------------------------------------+// Constants & Helpers+// ---------------------------------------------------------------------------++const MOBILE_BREAKPOINT = 768+const SPREAD_FACTOR = 1.2+const MAX_DPR = 2++function hexToRgba(hex: string, alpha: number) {+ const clean = hex.replace("#", "").trim()+ const full =+ clean.length === 3+ ? clean+ .split("")+ .map((c) => c + c)+ .join("")+ : clean++ if (!/^[0-9a-f]{6}$/i.test(full)) return `rgba(139,92,246,${alpha})`++ const n = Number.parseInt(full, 16)+ return `rgba(${(n >> 16) & 0xff},${(n >> 8) & 0xff},${n & 0xff},${alpha})`+}++function deriveProjection(depth: number) {+ const t = Math.max(0, Math.min(1, depth))+ const fov = 800 - t * 600 // [800, 200]+ const perspectiveDistance = 100 + t * 700 // [100, 800]+ // depthRange stays below fov + pd - 1 to ensure positive denominator+ const depthRange = t * Math.min(400, fov + perspectiveDistance - 1)+ return { fov, perspectiveDistance, depthRange }+}++function spawnParticle(+ width: number,+ height: number,+ size: number,+ opacity: number+): Particle {+ const sizeVariance = size * 0.4+ const opacityVariance = 0.2+ return {+ angle: Math.random() * Math.PI * 2,+ radius: Math.random() * Math.max(width, height) * SPREAD_FACTOR,+ y: (Math.random() - 0.5) * height * 2,+ size: Math.max(0.5, size - sizeVariance + Math.random() * sizeVariance * 2),+ angularSpeed: 0.0015 + Math.random() * 0.001,+ opacity: Math.min(+ 1,+ Math.max(+ 0,+ opacity - opacityVariance + Math.random() * opacityVariance * 2+ )+ ),+ screenX: 0,+ screenY: 0,+ projectedScale: 1,+ }+}++// ---------------------------------------------------------------------------+// Component+// ---------------------------------------------------------------------------++export function Floating3DParticles({+ quantity = 400,+ color = "#8B5CF6",+ size = 5,+ opacity = 0.3,+ drift = 0.8,+ depth = 0.5,+ className,+ style,+ ...canvasProps+}: Floating3DParticlesProps) {+ const canvasRef = React.useRef<HTMLCanvasElement>(null)+ const ioRef = React.useRef<IntersectionObserver | null>(null)+ const stateRef = React.useRef({+ mounted: false,+ paused: false,+ reducedMotion: false,+ rafId: null as number | null,+ })++ // Read fresh on every frame, so recolouring (e.g. a theme switch) does not+ // tear down the effect and respawn the whole field.+ const colorRef = React.useRef(color)+ colorRef.current = color++ React.useEffect(() => {+ const canvas = canvasRef.current+ if (!canvas) return+ const ctx = canvas.getContext("2d", { alpha: true })+ if (!ctx) return++ const s = stateRef.current+ s.mounted = true+ s.paused = false++ let width = 0+ let height = 0+ let particles: Particle[] = []+ let staticDirty = true++ const { fov, perspectiveDistance, depthRange } = deriveProjection(depth)++ // Reduced-motion media query (built-in a11y best practice)+ const mq = window.matchMedia("(prefers-reduced-motion: reduce)")+ const syncReducedMotion = () => {+ s.reducedMotion = mq.matches+ }+ syncReducedMotion()++ // Draw single particle+ const draw = (p: Particle) => {+ const r = Math.max(0, p.size * p.projectedScale)+ if (r <= 0) return++ ctx.beginPath()+ ctx.fillStyle = hexToRgba(colorRef.current, p.opacity)+ ctx.arc(p.screenX, p.screenY, r, 0, Math.PI * 2)+ ctx.fill()+ }++ // Static frame for reduced motion+ const staticFrame = () => {+ ctx.clearRect(0, 0, width, height)+ const cx = width / 2+ const cy = height / 2++ for (const p of particles) {+ const denom = Math.max(1, fov + perspectiveDistance)+ const scale = fov / denom+ p.screenX = cx + Math.cos(p.angle) * p.radius * scale+ p.screenY = cy + p.y * scale+ p.projectedScale = scale+ draw(p)+ }+ }++ // Animation loop: continuous 3D field rotation and buoyant drift+ const tick = () => {+ if (!s.mounted) return++ if (s.paused) {+ s.rafId = requestAnimationFrame(tick)+ return+ }++ // Reduced motion: paint one static frame, then idle until something+ // invalidates it (resize, or the motion preference being turned off).+ if (s.reducedMotion) {+ if (staticDirty) {+ staticDirty = false+ staticFrame()+ }+ s.rafId = requestAnimationFrame(tick)+ return+ }++ staticDirty = true++ ctx.clearRect(0, 0, width, height)++ const cx = width / 2+ const cy = height / 2++ for (const p of particles) {+ // Continuous organic rotation around the 3D central axis+ p.angle += p.angularSpeed+ p.y -= drift++ // Respawn on the opposite edge, whichever one the particle left+ // through, so a negative drift falls instead of draining the field+ if (p.y < -height) {+ p.y = height+ p.radius = Math.random() * Math.max(width, height) * SPREAD_FACTOR+ } else if (p.y > height) {+ p.y = -height+ p.radius = Math.random() * Math.max(width, height) * SPREAD_FACTOR+ }++ // 3D Perspective Projection+ const denom = Math.max(+ 1,+ fov + perspectiveDistance + Math.sin(p.angle) * depthRange+ )+ const scale = fov / denom++ p.screenX = cx + Math.cos(p.angle) * p.radius * scale+ p.screenY = cy + p.y * scale+ p.projectedScale = scale+ }++ // Painter's algorithm: draw farthest particles first+ particles.sort((a, b) => a.projectedScale - b.projectedScale)+ for (const p of particles) draw(p)++ s.rafId = requestAnimationFrame(tick)+ }++ // Resize handling with automatic mobile count scaling+ const resize = () => {+ const rect = canvas.getBoundingClientRect()+ width = Math.max(1, Math.round(rect.width))+ height = Math.max(1, Math.round(rect.height))++ const dpr = Math.max(1, Math.min(window.devicePixelRatio || 1, MAX_DPR))+ canvas.width = Math.round(width * dpr)+ canvas.height = Math.round(height * dpr)+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)++ const isMobile = window.innerWidth < MOBILE_BREAKPOINT+ const count = isMobile ? Math.round(quantity * 0.2) : quantity++ particles = Array.from({ length: Math.max(0, count) }, () =>+ spawnParticle(width, height, size, opacity)+ )++ // Canvas was cleared by the width/height reassignment above.+ staticDirty = true+ }++ const onVisibilityChange = () => {+ s.paused = document.hidden+ }++ // ResizeObserver+ const ro =+ typeof ResizeObserver !== "undefined" ? new ResizeObserver(resize) : null+ if (ro) {+ ro.observe(canvas)+ } else {+ window.addEventListener("resize", resize)+ }++ // IntersectionObserver (built-in performance pause off-screen)+ if (typeof IntersectionObserver !== "undefined") {+ ioRef.current = new IntersectionObserver(+ ([entry]) => {+ if (entry) s.paused = document.hidden || !entry.isIntersecting+ },+ { threshold: 0 }+ )+ ioRef.current.observe(canvas)+ }++ document.addEventListener("visibilitychange", onVisibilityChange)+ mq.addEventListener("change", syncReducedMotion)++ resize()+ s.rafId = requestAnimationFrame(tick)++ return () => {+ s.mounted = false+ if (s.rafId !== null) {+ cancelAnimationFrame(s.rafId)+ s.rafId = null+ }+ ro?.disconnect()+ if (!ro) window.removeEventListener("resize", resize)+ ioRef.current?.disconnect()+ ioRef.current = null+ document.removeEventListener("visibilitychange", onVisibilityChange)+ mq.removeEventListener("change", syncReducedMotion)+ }+ }, [quantity, size, opacity, drift, depth])++ return (+ <canvas+ ref={canvasRef}+ aria-hidden="true"+ className={cn(+ "pointer-events-none absolute inset-0 h-full w-full",+ className+ )}+ style={style}+ {...canvasProps}+ />+ )+}+++===== EXAMPLE: floating-3d-particles-demo =====+Title: Floating 3D Particles Demo++--- file: example/floating-3d-particles-demo.tsx ---+"use client"++import { ArrowRight } from "lucide-react"+import { useTheme } from "next-themes"++import { Floating3DParticles } from "@/registry/magicui/floating-3d-particles"++export default function Component() {+ const { resolvedTheme } = useTheme()+ const color = resolvedTheme === "dark" ? "#ffffff" : "#000000"++ return (+ <div className="bg-background relative flex h-[500px] w-full items-center justify-center overflow-hidden rounded-lg border">+ <Floating3DParticles color={color} />++ <div className="relative z-10 flex flex-col items-center gap-6 px-6 text-center">+ <h2 className="text-3xl font-bold tracking-tight md:text-5xl">+ Build something magical+ </h2>+ <p className="text-muted-foreground max-w-xl text-base md:text-lg">+ A pseudo-3D particle background that stays behind your content with+ continuous rotation and buoyant drift.+ </p>+ <button+ type="button"+ className="bg-foreground text-background inline-flex h-11 items-center gap-2 rounded-lg px-6 font-medium no-underline transition-opacity hover:opacity-90"+ >+ Get Started+ <ArrowRight className="size-4" />+ </button>+ </div>+ </div>+ )+}+++===== EXAMPLE: floating-3d-particles-demo-2 =====+Title: Floating 3D Particles Demo 2++--- file: example/floating-3d-particles-demo-2.tsx ---+"use client"++import { useTheme } from "next-themes"++import { Floating3DParticles } from "@/registry/magicui/floating-3d-particles"++export default function Component() {+ const { resolvedTheme } = useTheme()+ const color = resolvedTheme === "dark" ? "#c4b5fd" : "#6d28d9"++ return (+ <div className="bg-background relative h-[500px] w-full overflow-hidden rounded-lg border">+ <Floating3DParticles+ color={color}+ depth={0.8}+ opacity={0.55}+ quantity={1000}+ />+ </div>+ )+}+++===== COMPONENT: glare-hover =====Title: Glare HoverDescription: A diagonal glare on hover using a ::before gradient and CSS variables (angle, size, duration, color).diff --git a/apps/www/public/llms.txt b/apps/www/public/llms.txtindex a375dac2..9427cbe8 100644--- a/apps/www/public/llms.txt+++ b/apps/www/public/llms.txt@@ -31,6 +31,7 @@ This file provides LLM-friendly entry points to documentation and examples.- [Dotted Map](https://magicui.design/docs/components/dotted-map): A component with a dotted map.- [File Tree](https://magicui.design/docs/components/file-tree): A component used to showcase the folder and file structure of a directory.- [Flickering Grid](https://magicui.design/docs/components/flickering-grid): A flickering grid background made with SVGs, fully customizable using Tailwind CSS.+- [Floating 3D Particles](https://magicui.design/docs/components/floating-3d-particles): A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.- [Glare Hover](https://magicui.design/docs/components/glare-hover): A diagonal glare on hover using a ::before gradient and CSS variables (angle, size, duration, color).- [Globe](https://magicui.design/docs/components/globe): An autorotating, interactive, and highly performant globe made using WebGL.- [Glyph Matrix](https://magicui.design/docs/components/glyph-matrix): An animated grid of subtly shifting glyphs with fade effect and theme support.@@ -254,6 +255,8 @@ This file provides LLM-friendly entry points to documentation and examples.- [kinetic-text-demo](https://github.com/magicuidesign/magicui/blob/main/example/kinetic-text-demo.tsx): Example usage- [Text 3D Flip Demo](https://github.com/magicuidesign/magicui/blob/main/example/text-3d-flip-demo.tsx): Example usage- [Text 3D Flip Demo 2](https://github.com/magicuidesign/magicui/blob/main/example/text-3d-flip-demo-2.tsx): Example usage+- [Floating 3D Particles Demo](https://github.com/magicuidesign/magicui/blob/main/example/floating-3d-particles-demo.tsx): Example usage+- [Floating 3D Particles Demo 2](https://github.com/magicuidesign/magicui/blob/main/example/floating-3d-particles-demo-2.tsx): Example usage## Optionaldiff --git a/apps/www/public/r/floating-3d-particles-demo-2.json b/apps/www/public/r/floating-3d-particles-demo-2.jsonnew file mode 100644index 00000000..0457b54f--- /dev/null+++ b/apps/www/public/r/floating-3d-particles-demo-2.json@@ -0,0 +1,20 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "floating-3d-particles-demo-2",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo 2",+ "description": "Example showing the particle field as a standalone background.",+ "dependencies": [+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo-2.tsx",+ "content": "\"use client\"\n\nimport { useTheme } from \"next-themes\"\n\nimport { Floating3DParticles } from \"@/registry/magicui/floating-3d-particles\"\n\nexport default function Component() {\n const { resolvedTheme } = useTheme()\n const color = resolvedTheme === \"dark\" ? \"#c4b5fd\" : \"#6d28d9\"\n\n return (\n <div className=\"bg-background relative h-[500px] w-full overflow-hidden rounded-lg border\">\n <Floating3DParticles\n color={color}\n depth={0.8}\n opacity={0.55}\n quantity={1000}\n />\n </div>\n )\n}\n",+ "type": "registry:example"+ }+ ]+}\ No newline at end of filediff --git a/apps/www/public/r/floating-3d-particles-demo.json b/apps/www/public/r/floating-3d-particles-demo.jsonnew file mode 100644index 00000000..ac2cd99f--- /dev/null+++ b/apps/www/public/r/floating-3d-particles-demo.json@@ -0,0 +1,21 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "floating-3d-particles-demo",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo",+ "description": "Example showing a floating 3D particle field behind hero content.",+ "dependencies": [+ "lucide-react",+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo.tsx",+ "content": "\"use client\"\n\nimport { ArrowRight } from \"lucide-react\"\nimport { useTheme } from \"next-themes\"\n\nimport { Floating3DParticles } from \"@/registry/magicui/floating-3d-particles\"\n\nexport default function Component() {\n const { resolvedTheme } = useTheme()\n const color = resolvedTheme === \"dark\" ? \"#ffffff\" : \"#000000\"\n\n return (\n <div className=\"bg-background relative flex h-[500px] w-full items-center justify-center overflow-hidden rounded-lg border\">\n <Floating3DParticles color={color} />\n\n <div className=\"relative z-10 flex flex-col items-center gap-6 px-6 text-center\">\n <h2 className=\"text-3xl font-bold tracking-tight md:text-5xl\">\n Build something magical\n </h2>\n <p className=\"text-muted-foreground max-w-xl text-base md:text-lg\">\n A pseudo-3D particle background that stays behind your content with\n continuous rotation and buoyant drift.\n </p>\n <button\n type=\"button\"\n className=\"bg-foreground text-background inline-flex h-11 items-center gap-2 rounded-lg px-6 font-medium no-underline transition-opacity hover:opacity-90\"\n >\n Get Started\n <ArrowRight className=\"size-4\" />\n </button>\n </div>\n </div>\n )\n}\n",+ "type": "registry:example"+ }+ ]+}\ No newline at end of filediff --git a/apps/www/public/r/floating-3d-particles.json b/apps/www/public/r/floating-3d-particles.jsonnew file mode 100644index 00000000..86548eca--- /dev/null+++ b/apps/www/public/r/floating-3d-particles.json@@ -0,0 +1,14 @@+{+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",+ "name": "floating-3d-particles",+ "type": "registry:ui",+ "title": "Floating 3D Particles",+ "description": "A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.",+ "files": [+ {+ "path": "registry/magicui/floating-3d-particles.tsx",+ "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport interface Floating3DParticlesProps extends Omit<\n React.CanvasHTMLAttributes<HTMLCanvasElement>,\n \"width\" | \"height\"\n> {\n /**\n * Number of particles rendered on desktop viewports.\n * On mobile screens (< 768px), particle count automatically scales down\n * to 20 % to preserve smooth frame rates.\n * @default 400\n */\n quantity?: number\n /**\n * Particle color — 3 or 6 digit hex string.\n * @default \"#8B5CF6\"\n */\n color?: string\n /**\n * Mean particle radius in px. Each particle is randomly assigned a size\n * within ±40 % of this value.\n * @default 5\n */\n size?: number\n /**\n * Mean particle opacity (0–1). Each particle randomly varies within\n * ±0.2 of this value, clamped to [0, 1].\n * @default 0.3\n */\n opacity?: number\n /**\n * Vertical floating speed in px per frame. Positive values drift upward,\n * negative values downward.\n * @default 0.8\n */\n drift?: number\n /**\n * 3-D depth intensity on a 0–1 scale. `0` produces a flat 2D plane; `1`\n * creates strong perspective with pronounced near/far scaling.\n * @default 0.5\n */\n depth?: number\n}\n\n// ---------------------------------------------------------------------------\n// Particle State (Polar coordinates + 3D perspective projection)\n// ---------------------------------------------------------------------------\n\ninterface Particle {\n angle: number\n radius: number\n y: number\n size: number\n angularSpeed: number\n opacity: number\n screenX: number\n screenY: number\n projectedScale: number\n}\n\n// ---------------------------------------------------------------------------\n// Constants & Helpers\n// ---------------------------------------------------------------------------\n\nconst MOBILE_BREAKPOINT = 768\nconst SPREAD_FACTOR = 1.2\nconst MAX_DPR = 2\n\nfunction hexToRgba(hex: string, alpha: number) {\n const clean = hex.replace(\"#\", \"\").trim()\n const full =\n clean.length === 3\n ? clean\n .split(\"\")\n .map((c) => c + c)\n .join(\"\")\n : clean\n\n if (!/^[0-9a-f]{6}$/i.test(full)) return `rgba(139,92,246,${alpha})`\n\n const n = Number.parseInt(full, 16)\n return `rgba(${(n >> 16) & 0xff},${(n >> 8) & 0xff},${n & 0xff},${alpha})`\n}\n\nfunction deriveProjection(depth: number) {\n const t = Math.max(0, Math.min(1, depth))\n const fov = 800 - t * 600 // [800, 200]\n const perspectiveDistance = 100 + t * 700 // [100, 800]\n // depthRange stays below fov + pd - 1 to ensure positive denominator\n const depthRange = t * Math.min(400, fov + perspectiveDistance - 1)\n return { fov, perspectiveDistance, depthRange }\n}\n\nfunction spawnParticle(\n width: number,\n height: number,\n size: number,\n opacity: number\n): Particle {\n const sizeVariance = size * 0.4\n const opacityVariance = 0.2\n return {\n angle: Math.random() * Math.PI * 2,\n radius: Math.random() * Math.max(width, height) * SPREAD_FACTOR,\n y: (Math.random() - 0.5) * height * 2,\n size: Math.max(0.5, size - sizeVariance + Math.random() * sizeVariance * 2),\n angularSpeed: 0.0015 + Math.random() * 0.001,\n opacity: Math.min(\n 1,\n Math.max(\n 0,\n opacity - opacityVariance + Math.random() * opacityVariance * 2\n )\n ),\n screenX: 0,\n screenY: 0,\n projectedScale: 1,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\nexport function Floating3DParticles({\n quantity = 400,\n color = \"#8B5CF6\",\n size = 5,\n opacity = 0.3,\n drift = 0.8,\n depth = 0.5,\n className,\n style,\n ...canvasProps\n}: Floating3DParticlesProps) {\n const canvasRef = React.useRef<HTMLCanvasElement>(null)\n const ioRef = React.useRef<IntersectionObserver | null>(null)\n const stateRef = React.useRef({\n mounted: false,\n paused: false,\n reducedMotion: false,\n rafId: null as number | null,\n })\n\n // Read fresh on every frame, so recolouring (e.g. a theme switch) does not\n // tear down the effect and respawn the whole field.\n const colorRef = React.useRef(color)\n colorRef.current = color\n\n React.useEffect(() => {\n const canvas = canvasRef.current\n if (!canvas) return\n const ctx = canvas.getContext(\"2d\", { alpha: true })\n if (!ctx) return\n\n const s = stateRef.current\n s.mounted = true\n s.paused = false\n\n let width = 0\n let height = 0\n let particles: Particle[] = []\n let staticDirty = true\n\n const { fov, perspectiveDistance, depthRange } = deriveProjection(depth)\n\n // Reduced-motion media query (built-in a11y best practice)\n const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n const syncReducedMotion = () => {\n s.reducedMotion = mq.matches\n }\n syncReducedMotion()\n\n // Draw single particle\n const draw = (p: Particle) => {\n const r = Math.max(0, p.size * p.projectedScale)\n if (r <= 0) return\n\n ctx.beginPath()\n ctx.fillStyle = hexToRgba(colorRef.current, p.opacity)\n ctx.arc(p.screenX, p.screenY, r, 0, Math.PI * 2)\n ctx.fill()\n }\n\n // Static frame for reduced motion\n const staticFrame = () => {\n ctx.clearRect(0, 0, width, height)\n const cx = width / 2\n const cy = height / 2\n\n for (const p of particles) {\n const denom = Math.max(1, fov + perspectiveDistance)\n const scale = fov / denom\n p.screenX = cx + Math.cos(p.angle) * p.radius * scale\n p.screenY = cy + p.y * scale\n p.projectedScale = scale\n draw(p)\n }\n }\n\n // Animation loop: continuous 3D field rotation and buoyant drift\n const tick = () => {\n if (!s.mounted) return\n\n if (s.paused) {\n s.rafId = requestAnimationFrame(tick)\n return\n }\n\n // Reduced motion: paint one static frame, then idle until something\n // invalidates it (resize, or the motion preference being turned off).\n if (s.reducedMotion) {\n if (staticDirty) {\n staticDirty = false\n staticFrame()\n }\n s.rafId = requestAnimationFrame(tick)\n return\n }\n\n staticDirty = true\n\n ctx.clearRect(0, 0, width, height)\n\n const cx = width / 2\n const cy = height / 2\n\n for (const p of particles) {\n // Continuous organic rotation around the 3D central axis\n p.angle += p.angularSpeed\n p.y -= drift\n\n // Respawn on the opposite edge, whichever one the particle left\n // through, so a negative drift falls instead of draining the field\n if (p.y < -height) {\n p.y = height\n p.radius = Math.random() * Math.max(width, height) * SPREAD_FACTOR\n } else if (p.y > height) {\n p.y = -height\n p.radius = Math.random() * Math.max(width, height) * SPREAD_FACTOR\n }\n\n // 3D Perspective Projection\n const denom = Math.max(\n 1,\n fov + perspectiveDistance + Math.sin(p.angle) * depthRange\n )\n const scale = fov / denom\n\n p.screenX = cx + Math.cos(p.angle) * p.radius * scale\n p.screenY = cy + p.y * scale\n p.projectedScale = scale\n }\n\n // Painter's algorithm: draw farthest particles first\n particles.sort((a, b) => a.projectedScale - b.projectedScale)\n for (const p of particles) draw(p)\n\n s.rafId = requestAnimationFrame(tick)\n }\n\n // Resize handling with automatic mobile count scaling\n const resize = () => {\n const rect = canvas.getBoundingClientRect()\n width = Math.max(1, Math.round(rect.width))\n height = Math.max(1, Math.round(rect.height))\n\n const dpr = Math.max(1, Math.min(window.devicePixelRatio || 1, MAX_DPR))\n canvas.width = Math.round(width * dpr)\n canvas.height = Math.round(height * dpr)\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n\n const isMobile = window.innerWidth < MOBILE_BREAKPOINT\n const count = isMobile ? Math.round(quantity * 0.2) : quantity\n\n particles = Array.from({ length: Math.max(0, count) }, () =>\n spawnParticle(width, height, size, opacity)\n )\n\n // Canvas was cleared by the width/height reassignment above.\n staticDirty = true\n }\n\n const onVisibilityChange = () => {\n s.paused = document.hidden\n }\n\n // ResizeObserver\n const ro =\n typeof ResizeObserver !== \"undefined\" ? new ResizeObserver(resize) : null\n if (ro) {\n ro.observe(canvas)\n } else {\n window.addEventListener(\"resize\", resize)\n }\n\n // IntersectionObserver (built-in performance pause off-screen)\n if (typeof IntersectionObserver !== \"undefined\") {\n ioRef.current = new IntersectionObserver(\n ([entry]) => {\n if (entry) s.paused = document.hidden || !entry.isIntersecting\n },\n { threshold: 0 }\n )\n ioRef.current.observe(canvas)\n }\n\n document.addEventListener(\"visibilitychange\", onVisibilityChange)\n mq.addEventListener(\"change\", syncReducedMotion)\n\n resize()\n s.rafId = requestAnimationFrame(tick)\n\n return () => {\n s.mounted = false\n if (s.rafId !== null) {\n cancelAnimationFrame(s.rafId)\n s.rafId = null\n }\n ro?.disconnect()\n if (!ro) window.removeEventListener(\"resize\", resize)\n ioRef.current?.disconnect()\n ioRef.current = null\n document.removeEventListener(\"visibilitychange\", onVisibilityChange)\n mq.removeEventListener(\"change\", syncReducedMotion)\n }\n }, [quantity, size, opacity, drift, depth])\n\n return (\n <canvas\n ref={canvasRef}\n aria-hidden=\"true\"\n className={cn(\n \"pointer-events-none absolute inset-0 h-full w-full\",\n className\n )}\n style={style}\n {...canvasProps}\n />\n )\n}\n",+ "type": "registry:ui"+ }+ ]+}\ No newline at end of filediff --git a/apps/www/public/r/registry.json b/apps/www/public/r/registry.jsonindex 4662fd09..a0d5d0d2 100644--- a/apps/www/public/r/registry.json+++ b/apps/www/public/r/registry.json@@ -1365,6 +1365,18 @@}]},+ {+ "name": "floating-3d-particles",+ "type": "registry:ui",+ "title": "Floating 3D Particles",+ "description": "A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.",+ "files": [+ {+ "path": "registry/magicui/floating-3d-particles.tsx",+ "type": "registry:ui"+ }+ ]+ },{"name": "magic-card-demo","type": "registry:example",@@ -3955,6 +3967,43 @@}]},+ {+ "name": "floating-3d-particles-demo",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo",+ "description": "Example showing a floating 3D particle field behind hero content.",+ "dependencies": [+ "lucide-react",+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo.tsx",+ "type": "registry:example"+ }+ ]+ },+ {+ "name": "floating-3d-particles-demo-2",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo 2",+ "description": "Example showing the particle field as a standalone background.",+ "dependencies": [+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo-2.tsx",+ "type": "registry:example"+ }+ ]+ },{"name": "utils","type": "registry:lib",diff --git a/apps/www/public/registry.json b/apps/www/public/registry.jsonindex 4662fd09..a0d5d0d2 100644--- a/apps/www/public/registry.json+++ b/apps/www/public/registry.json@@ -1365,6 +1365,18 @@}]},+ {+ "name": "floating-3d-particles",+ "type": "registry:ui",+ "title": "Floating 3D Particles",+ "description": "A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.",+ "files": [+ {+ "path": "registry/magicui/floating-3d-particles.tsx",+ "type": "registry:ui"+ }+ ]+ },{"name": "magic-card-demo","type": "registry:example",@@ -3955,6 +3967,43 @@}]},+ {+ "name": "floating-3d-particles-demo",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo",+ "description": "Example showing a floating 3D particle field behind hero content.",+ "dependencies": [+ "lucide-react",+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo.tsx",+ "type": "registry:example"+ }+ ]+ },+ {+ "name": "floating-3d-particles-demo-2",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo 2",+ "description": "Example showing the particle field as a standalone background.",+ "dependencies": [+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo-2.tsx",+ "type": "registry:example"+ }+ ]+ },{"name": "utils","type": "registry:lib",diff --git a/apps/www/registry.json b/apps/www/registry.jsonindex 4662fd09..a0d5d0d2 100644--- a/apps/www/registry.json+++ b/apps/www/registry.json@@ -1365,6 +1365,18 @@}]},+ {+ "name": "floating-3d-particles",+ "type": "registry:ui",+ "title": "Floating 3D Particles",+ "description": "A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.",+ "files": [+ {+ "path": "registry/magicui/floating-3d-particles.tsx",+ "type": "registry:ui"+ }+ ]+ },{"name": "magic-card-demo","type": "registry:example",@@ -3955,6 +3967,43 @@}]},+ {+ "name": "floating-3d-particles-demo",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo",+ "description": "Example showing a floating 3D particle field behind hero content.",+ "dependencies": [+ "lucide-react",+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo.tsx",+ "type": "registry:example"+ }+ ]+ },+ {+ "name": "floating-3d-particles-demo-2",+ "type": "registry:example",+ "title": "Floating 3D Particles Demo 2",+ "description": "Example showing the particle field as a standalone background.",+ "dependencies": [+ "next-themes"+ ],+ "registryDependencies": [+ "@magicui/floating-3d-particles"+ ],+ "files": [+ {+ "path": "registry/example/floating-3d-particles-demo-2.tsx",+ "type": "registry:example"+ }+ ]+ },{"name": "utils","type": "registry:lib",diff --git a/apps/www/registry/__index__.tsx b/apps/www/registry/__index__.tsxindex dfc82315..09614eec 100644--- a/apps/www/registry/__index__.tsx+++ b/apps/www/registry/__index__.tsx@@ -1324,6 +1324,23 @@ export const Index: Record<string, any> = {}),meta: undefined,},+ "floating-3d-particles": {+ name: "floating-3d-particles",+ description: "A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.",+ type: "registry:ui",+ registryDependencies: undefined,+ files: [{+ path: "registry/magicui/floating-3d-particles.tsx",+ type: "registry:ui",+ target: ""+ }],+ component: React.lazy(async () => {+ const mod = await import("@/registry/magicui/floating-3d-particles.tsx")+ const exportName = Object.keys(mod).find(key => typeof mod[key] === 'function' || typeof mod[key] === 'object') ?? item.name+ return { default: mod.default ?? mod[exportName] }+ }),+ meta: undefined,+ },"magic-card-demo": {name: "magic-card-demo",description: "Example showing a spotlight effect that follows your mouse cursor and highlights borders on hover.",@@ -4184,6 +4201,40 @@ export const Index: Record<string, any> = {}),meta: undefined,},+ "floating-3d-particles-demo": {+ name: "floating-3d-particles-demo",+ description: "Example showing a floating 3D particle field behind hero content.",+ type: "registry:example",+ registryDependencies: ["@magicui/floating-3d-particles"],+ files: [{+ path: "registry/example/floating-3d-particles-demo.tsx",+ type: "registry:example",+ target: ""+ }],+ component: React.lazy(async () => {+ const mod = await import("@/registry/example/floating-3d-particles-demo.tsx")+ const exportName = Object.keys(mod).find(key => typeof mod[key] === 'function' || typeof mod[key] === 'object') ?? item.name+ return { default: mod.default ?? mod[exportName] }+ }),+ meta: undefined,+ },+ "floating-3d-particles-demo-2": {+ name: "floating-3d-particles-demo-2",+ description: "Example showing the particle field as a standalone background.",+ type: "registry:example",+ registryDependencies: ["@magicui/floating-3d-particles"],+ files: [{+ path: "registry/example/floating-3d-particles-demo-2.tsx",+ type: "registry:example",+ target: ""+ }],+ component: React.lazy(async () => {+ const mod = await import("@/registry/example/floating-3d-particles-demo-2.tsx")+ const exportName = Object.keys(mod).find(key => typeof mod[key] === 'function' || typeof mod[key] === 'object') ?? item.name+ return { default: mod.default ?? mod[exportName] }+ }),+ meta: undefined,+ },"utils": {name: "utils",description: "",diff --git a/apps/www/registry/example/floating-3d-particles-demo-2.tsx b/apps/www/registry/example/floating-3d-particles-demo-2.tsxnew file mode 100644index 00000000..65f949a2--- /dev/null+++ b/apps/www/registry/example/floating-3d-particles-demo-2.tsx@@ -0,0 +1,21 @@+"use client"++import { useTheme } from "next-themes"++import { Floating3DParticles } from "@/registry/magicui/floating-3d-particles"++export default function Component() {+ const { resolvedTheme } = useTheme()+ const color = resolvedTheme === "dark" ? "#c4b5fd" : "#6d28d9"++ return (+ <div className="bg-background relative h-[500px] w-full overflow-hidden rounded-lg border">+ <Floating3DParticles+ color={color}+ depth={0.8}+ opacity={0.55}+ quantity={1000}+ />+ </div>+ )+}diff --git a/apps/www/registry/example/floating-3d-particles-demo.tsx b/apps/www/registry/example/floating-3d-particles-demo.tsxnew file mode 100644index 00000000..ddfbe5cc--- /dev/null+++ b/apps/www/registry/example/floating-3d-particles-demo.tsx@@ -0,0 +1,34 @@+"use client"++import { ArrowRight } from "lucide-react"+import { useTheme } from "next-themes"++import { Floating3DParticles } from "@/registry/magicui/floating-3d-particles"++export default function Component() {+ const { resolvedTheme } = useTheme()+ const color = resolvedTheme === "dark" ? "#ffffff" : "#000000"++ return (+ <div className="bg-background relative flex h-[500px] w-full items-center justify-center overflow-hidden rounded-lg border">+ <Floating3DParticles color={color} />++ <div className="relative z-10 flex flex-col items-center gap-6 px-6 text-center">+ <h2 className="text-3xl font-bold tracking-tight md:text-5xl">+ Build something magical+ </h2>+ <p className="text-muted-foreground max-w-xl text-base md:text-lg">+ A pseudo-3D particle background that stays behind your content with+ continuous rotation and buoyant drift.+ </p>+ <button+ type="button"+ className="bg-foreground text-background inline-flex h-11 items-center gap-2 rounded-lg px-6 font-medium no-underline transition-opacity hover:opacity-90"+ >+ Get Started+ <ArrowRight className="size-4" />+ </button>+ </div>+ </div>+ )+}diff --git a/apps/www/registry/magicui/floating-3d-particles.tsx b/apps/www/registry/magicui/floating-3d-particles.tsxnew file mode 100644index 00000000..4e052015--- /dev/null+++ b/apps/www/registry/magicui/floating-3d-particles.tsx@@ -0,0 +1,345 @@+"use client"++import * as React from "react"++import { cn } from "@/lib/utils"++export interface Floating3DParticlesProps extends Omit<+ React.CanvasHTMLAttributes<HTMLCanvasElement>,+ "width" | "height"+> {+ /**+ * Number of particles rendered on desktop viewports.+ * On mobile screens (< 768px), particle count automatically scales down+ * to 20 % to preserve smooth frame rates.+ * @default 400+ */+ quantity?: number+ /**+ * Particle color — 3 or 6 digit hex string.+ * @default "#8B5CF6"+ */+ color?: string+ /**+ * Mean particle radius in px. Each particle is randomly assigned a size+ * within ±40 % of this value.+ * @default 5+ */+ size?: number+ /**+ * Mean particle opacity (0–1). Each particle randomly varies within+ * ±0.2 of this value, clamped to [0, 1].+ * @default 0.3+ */+ opacity?: number+ /**+ * Vertical floating speed in px per frame. Positive values drift upward,+ * negative values downward.+ * @default 0.8+ */+ drift?: number+ /**+ * 3-D depth intensity on a 0–1 scale. `0` produces a flat 2D plane; `1`+ * creates strong perspective with pronounced near/far scaling.+ * @default 0.5+ */+ depth?: number+}++// ---------------------------------------------------------------------------+// Particle State (Polar coordinates + 3D perspective projection)+// ---------------------------------------------------------------------------++interface Particle {+ angle: number+ radius: number+ y: number+ size: number+ angularSpeed: number+ opacity: number+ screenX: number+ screenY: number+ projectedScale: number+}++// ---------------------------------------------------------------------------+// Constants & Helpers+// ---------------------------------------------------------------------------++const MOBILE_BREAKPOINT = 768+const SPREAD_FACTOR = 1.2+const MAX_DPR = 2++function hexToRgba(hex: string, alpha: number) {+ const clean = hex.replace("#", "").trim()+ const full =+ clean.length === 3+ ? clean+ .split("")+ .map((c) => c + c)+ .join("")+ : clean++ if (!/^[0-9a-f]{6}$/i.test(full)) return `rgba(139,92,246,${alpha})`++ const n = Number.parseInt(full, 16)+ return `rgba(${(n >> 16) & 0xff},${(n >> 8) & 0xff},${n & 0xff},${alpha})`+}++function deriveProjection(depth: number) {+ const t = Math.max(0, Math.min(1, depth))+ const fov = 800 - t * 600 // [800, 200]+ const perspectiveDistance = 100 + t * 700 // [100, 800]+ // depthRange stays below fov + pd - 1 to ensure positive denominator+ const depthRange = t * Math.min(400, fov + perspectiveDistance - 1)+ return { fov, perspectiveDistance, depthRange }+}++function spawnParticle(+ width: number,+ height: number,+ size: number,+ opacity: number+): Particle {+ const sizeVariance = size * 0.4+ const opacityVariance = 0.2+ return {+ angle: Math.random() * Math.PI * 2,+ radius: Math.random() * Math.max(width, height) * SPREAD_FACTOR,+ y: (Math.random() - 0.5) * height * 2,+ size: Math.max(0.5, size - sizeVariance + Math.random() * sizeVariance * 2),+ angularSpeed: 0.0015 + Math.random() * 0.001,+ opacity: Math.min(+ 1,+ Math.max(+ 0,+ opacity - opacityVariance + Math.random() * opacityVariance * 2+ )+ ),+ screenX: 0,+ screenY: 0,+ projectedScale: 1,+ }+}++// ---------------------------------------------------------------------------+// Component+// ---------------------------------------------------------------------------++export function Floating3DParticles({+ quantity = 400,+ color = "#8B5CF6",+ size = 5,+ opacity = 0.3,+ drift = 0.8,+ depth = 0.5,+ className,+ style,+ ...canvasProps+}: Floating3DParticlesProps) {+ const canvasRef = React.useRef<HTMLCanvasElement>(null)+ const ioRef = React.useRef<IntersectionObserver | null>(null)+ const stateRef = React.useRef({+ mounted: false,+ paused: false,+ reducedMotion: false,+ rafId: null as number | null,+ })++ // Read fresh on every frame, so recolouring (e.g. a theme switch) does not+ // tear down the effect and respawn the whole field.+ const colorRef = React.useRef(color)+ colorRef.current = color++ React.useEffect(() => {+ const canvas = canvasRef.current+ if (!canvas) return+ const ctx = canvas.getContext("2d", { alpha: true })+ if (!ctx) return++ const s = stateRef.current+ s.mounted = true+ s.paused = false++ let width = 0+ let height = 0+ let particles: Particle[] = []+ let staticDirty = true++ const { fov, perspectiveDistance, depthRange } = deriveProjection(depth)++ // Reduced-motion media query (built-in a11y best practice)+ const mq = window.matchMedia("(prefers-reduced-motion: reduce)")+ const syncReducedMotion = () => {+ s.reducedMotion = mq.matches+ }+ syncReducedMotion()++ // Draw single particle+ const draw = (p: Particle) => {+ const r = Math.max(0, p.size * p.projectedScale)+ if (r <= 0) return++ ctx.beginPath()+ ctx.fillStyle = hexToRgba(colorRef.current, p.opacity)+ ctx.arc(p.screenX, p.screenY, r, 0, Math.PI * 2)+ ctx.fill()+ }++ // Static frame for reduced motion+ const staticFrame = () => {+ ctx.clearRect(0, 0, width, height)+ const cx = width / 2+ const cy = height / 2++ for (const p of particles) {+ const denom = Math.max(1, fov + perspectiveDistance)+ const scale = fov / denom+ p.screenX = cx + Math.cos(p.angle) * p.radius * scale+ p.screenY = cy + p.y * scale+ p.projectedScale = scale+ draw(p)+ }+ }++ // Animation loop: continuous 3D field rotation and buoyant drift+ const tick = () => {+ if (!s.mounted) return++ if (s.paused) {+ s.rafId = requestAnimationFrame(tick)+ return+ }++ // Reduced motion: paint one static frame, then idle until something+ // invalidates it (resize, or the motion preference being turned off).+ if (s.reducedMotion) {+ if (staticDirty) {+ staticDirty = false+ staticFrame()+ }+ s.rafId = requestAnimationFrame(tick)+ return+ }++ staticDirty = true++ ctx.clearRect(0, 0, width, height)++ const cx = width / 2+ const cy = height / 2++ for (const p of particles) {+ // Continuous organic rotation around the 3D central axis+ p.angle += p.angularSpeed+ p.y -= drift++ // Respawn on the opposite edge, whichever one the particle left+ // through, so a negative drift falls instead of draining the field+ if (p.y < -height) {+ p.y = height+ p.radius = Math.random() * Math.max(width, height) * SPREAD_FACTOR+ } else if (p.y > height) {+ p.y = -height+ p.radius = Math.random() * Math.max(width, height) * SPREAD_FACTOR+ }++ // 3D Perspective Projection+ const denom = Math.max(+ 1,+ fov + perspectiveDistance + Math.sin(p.angle) * depthRange+ )+ const scale = fov / denom++ p.screenX = cx + Math.cos(p.angle) * p.radius * scale+ p.screenY = cy + p.y * scale+ p.projectedScale = scale+ }++ // Painter's algorithm: draw farthest particles first+ particles.sort((a, b) => a.projectedScale - b.projectedScale)+ for (const p of particles) draw(p)++ s.rafId = requestAnimationFrame(tick)+ }++ // Resize handling with automatic mobile count scaling+ const resize = () => {+ const rect = canvas.getBoundingClientRect()+ width = Math.max(1, Math.round(rect.width))+ height = Math.max(1, Math.round(rect.height))++ const dpr = Math.max(1, Math.min(window.devicePixelRatio || 1, MAX_DPR))+ canvas.width = Math.round(width * dpr)+ canvas.height = Math.round(height * dpr)+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)++ const isMobile = window.innerWidth < MOBILE_BREAKPOINT+ const count = isMobile ? Math.round(quantity * 0.2) : quantity++ particles = Array.from({ length: Math.max(0, count) }, () =>+ spawnParticle(width, height, size, opacity)+ )++ // Canvas was cleared by the width/height reassignment above.+ staticDirty = true+ }++ const onVisibilityChange = () => {+ s.paused = document.hidden+ }++ // ResizeObserver+ const ro =+ typeof ResizeObserver !== "undefined" ? new ResizeObserver(resize) : null+ if (ro) {+ ro.observe(canvas)+ } else {+ window.addEventListener("resize", resize)+ }++ // IntersectionObserver (built-in performance pause off-screen)+ if (typeof IntersectionObserver !== "undefined") {+ ioRef.current = new IntersectionObserver(+ ([entry]) => {+ if (entry) s.paused = document.hidden || !entry.isIntersecting+ },+ { threshold: 0 }+ )+ ioRef.current.observe(canvas)+ }++ document.addEventListener("visibilitychange", onVisibilityChange)+ mq.addEventListener("change", syncReducedMotion)++ resize()+ s.rafId = requestAnimationFrame(tick)++ return () => {+ s.mounted = false+ if (s.rafId !== null) {+ cancelAnimationFrame(s.rafId)+ s.rafId = null+ }+ ro?.disconnect()+ if (!ro) window.removeEventListener("resize", resize)+ ioRef.current?.disconnect()+ ioRef.current = null+ document.removeEventListener("visibilitychange", onVisibilityChange)+ mq.removeEventListener("change", syncReducedMotion)+ }+ }, [quantity, size, opacity, drift, depth])++ return (+ <canvas+ ref={canvasRef}+ aria-hidden="true"+ className={cn(+ "pointer-events-none absolute inset-0 h-full w-full",+ className+ )}+ style={style}+ {...canvasProps}+ />+ )+}diff --git a/apps/www/registry/registry-examples.ts b/apps/www/registry/registry-examples.tsindex eb8c8ff1..6e7af7f7 100644--- a/apps/www/registry/registry-examples.ts+++ b/apps/www/registry/registry-examples.ts@@ -2245,4 +2245,34 @@ export const examples: Registry["items"] = [},],},+ {+ name: "floating-3d-particles-demo",+ type: "registry:example",+ title: "Floating 3D Particles Demo",+ description:+ "Example showing a floating 3D particle field behind hero content.",+ registryDependencies: ["@magicui/floating-3d-particles"],+ dependencies: ["lucide-react", "next-themes"],+ files: [+ {+ path: "example/floating-3d-particles-demo.tsx",+ type: "registry:example",+ },+ ],+ },+ {+ name: "floating-3d-particles-demo-2",+ type: "registry:example",+ title: "Floating 3D Particles Demo 2",+ description:+ "Example showing the particle field as a standalone background.",+ registryDependencies: ["@magicui/floating-3d-particles"],+ dependencies: ["next-themes"],+ files: [+ {+ path: "example/floating-3d-particles-demo-2.tsx",+ type: "registry:example",+ },+ ],+ },]diff --git a/apps/www/registry/registry-ui.ts b/apps/www/registry/registry-ui.tsindex d42e6a09..e35ae011 100644--- a/apps/www/registry/registry-ui.ts+++ b/apps/www/registry/registry-ui.ts@@ -1313,4 +1313,17 @@ export const ui: Registry["items"] = [},],},+ {+ name: "floating-3d-particles",+ type: "registry:ui",+ title: "Floating 3D Particles",+ description:+ "A canvas-based pseudo-3D particle field with perspective projection, continuous rotation and buoyant drift.",+ files: [+ {+ path: "magicui/floating-3d-particles.tsx",+ type: "registry:ui",+ },+ ],+ },]