# Particle Morph Text
*URL: https://www.grettech.com/components/particle-text*

Words built from thousands of particles that swirl from one word into the next and scatter away from the cursor.

- Particles fly in to assemble each word, then morph to the next
- The cursor pushes particles aside; they spring back
- Gradient colours that adapt to light and dark mode
- Pauses off screen; with reduced motion, words simply swap

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/particle-text
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/particle-text-demo`

**Dependencies:** npm: clsx, tailwind-merge

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses and the shadcn/ui components it builds on. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install clsx tailwind-merge
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/particle-text.tsx`
```tsx
"use client"

import { cn } from "@/lib/utils"
import * as React from "react"

export interface ParticleTextProps extends React.HTMLAttributes<HTMLDivElement> {
  /** Words to cycle through */
  words: string[]
  /** ms each word stays before morphing to the next */
  interval?: number
  /** Gradient across the text, left to right. Defaults to a deeper palette
   * in light mode and a brighter one in dark mode. */
  colors?: string[]
  /** Distance between sampled points in px; smaller is denser */
  density?: number
  /** Particle size in px */
  particleSize?: number
  /** Cursor push radius in px; 0 turns it off */
  repelRadius?: number
  fontWeight?: number
  /** Accessible text. Defaults to the words joined. */
  label?: string
}

type Particle = {
  x: number
  y: number
  vx: number
  vy: number
  tx: number
  ty: number
  color: string
  alpha: number
  targetAlpha: number
}

/** Pixel positions that make up `word`, fitted to the canvas */
function sampleWord(
  word: string,
  width: number,
  height: number,
  density: number,
  fontWeight: number,
  fontFamily: string
) {
  const canvas = document.createElement("canvas")
  canvas.width = width
  canvas.height = height
  const ctx = canvas.getContext("2d", { willReadFrequently: true })!
  // Largest size that fits 90% of the width and 75% of the height
  let size = height * 0.75
  ctx.font = `${fontWeight} ${size}px ${fontFamily}`
  const measured = ctx.measureText(word).width
  if (measured > width * 0.9) size *= (width * 0.9) / measured
  ctx.font = `${fontWeight} ${size}px ${fontFamily}`
  ctx.textAlign = "center"
  ctx.textBaseline = "middle"
  ctx.fillStyle = "#fff"
  ctx.fillText(word, width / 2, height / 2)

  const data = ctx.getImageData(0, 0, width, height).data
  const points: { x: number; y: number }[] = []
  for (let y = 0; y < height; y += density) {
    for (let x = 0; x < width; x += density) {
      if (data[(y * width + x) * 4 + 3] > 128) points.push({ x, y })
    }
  }
  return points
}

const LIGHT_COLORS = ["#0891b2", "#7c3aed", "#db2777"]
const DARK_COLORS = ["#22d3ee", "#a78bfa", "#f472b6"]

/** Dark mode from the theme class (next-themes), else the OS setting */
function isDark() {
  const root = document.documentElement
  if (root.classList.contains("dark")) return true
  if (root.classList.contains("light")) return false
  return window.matchMedia("(prefers-color-scheme: dark)").matches
}

/** Colour at position t (0–1) along the gradient stops */
function mix(colors: string[], t: number, ctx: CanvasRenderingContext2D) {
  const parse = (c: string) => {
    ctx.fillStyle = c
    const hex = ctx.fillStyle as string
    return [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16))
  }
  if (colors.length === 1) return colors[0]
  const span = t * (colors.length - 1)
  const i = Math.min(Math.floor(span), colors.length - 2)
  const a = parse(colors[i])
  const b = parse(colors[i + 1])
  const f = span - i
  return `rgb(${a.map((v, k) => Math.round(v + (b[k] - v) * f)).join(",")})`
}

export const ParticleText = React.forwardRef<HTMLDivElement, ParticleTextProps>(
  (
    {
      words,
      interval = 3200,
      colors,
      density = 4,
      particleSize = 2.5,
      repelRadius = 90,
      fontWeight = 800,
      label,
      className,
      ...props
    },
    forwardedRef
  ) => {
    const wrapRef = React.useRef<HTMLDivElement>(null)
    React.useImperativeHandle(forwardedRef, () => wrapRef.current!)
    const canvasRef = React.useRef<HTMLCanvasElement>(null)
    const wordsKey = words.join("\u0000")
    const colorsKey = colors?.join(",") ?? ""

    React.useEffect(() => {
      const wrap = wrapRef.current
      const canvas = canvasRef.current
      if (!wrap || !canvas || words.length === 0) return
      const ctx = canvas.getContext("2d")!
      const reduceMotion = window.matchMedia(
        "(prefers-reduced-motion: reduce)"
      ).matches
      const fontFamily = getComputedStyle(wrap).fontFamily || "sans-serif"

      let width = 0
      let height = 0
      let particles: Particle[] = []
      let wordIndex = 0
      let raf = 0
      let timer: ReturnType<typeof setInterval> | undefined
      let visible = false
      const pointer = { x: -9999, y: -9999 }

      let palette = colors ?? (isDark() ? DARK_COLORS : LIGHT_COLORS)
      const colorCache = new Map<number, string>()
      const colorAt = (x: number) => {
        const key = Math.round((x / width) * 50)
        if (!colorCache.has(key))
          colorCache.set(key, mix(palette, key / 50, ctx))
        return colorCache.get(key)!
      }

      // Theme switches recolour the particles in place
      const onTheme = () => {
        if (colors) return
        const next = isDark() ? DARK_COLORS : LIGHT_COLORS
        if (next === palette) return
        palette = next
        colorCache.clear()
        for (const p of particles) p.color = colorAt(p.tx)
        if (!raf) draw()
      }
      const themeObserver = new MutationObserver(onTheme)
      themeObserver.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ["class", "data-theme"],
      })
      const scheme = window.matchMedia("(prefers-color-scheme: dark)")
      scheme.addEventListener("change", onTheme)

      // Assign every particle a point of the word; spare particles fade out
      const morphTo = (index: number, scatter: boolean) => {
        const points = sampleWord(
          words[index],
          width,
          height,
          density,
          fontWeight,
          fontFamily
        )
        // Shuffle so particles cross the canvas instead of sliding sideways
        for (let i = points.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1))
          ;[points[i], points[j]] = [points[j], points[i]]
        }
        while (particles.length < points.length) {
          particles.push({
            x: scatter ? Math.random() * width : width / 2,
            y: scatter ? Math.random() * height : height / 2,
            vx: 0,
            vy: 0,
            tx: 0,
            ty: 0,
            color: "",
            alpha: 0,
            targetAlpha: 1,
          })
        }
        particles.forEach((p, i) => {
          const point = points[i]
          if (point) {
            p.tx = point.x
            p.ty = point.y
            p.color = colorAt(point.x)
            p.targetAlpha = 1
          } else {
            // Drift to a random point and fade away
            const any = points[i % Math.max(points.length, 1)]
            p.tx = any ? any.x : p.x
            p.ty = any ? any.y : p.y
            p.targetAlpha = 0
          }
          if (reduceMotion) {
            p.x = p.tx
            p.y = p.ty
            p.alpha = p.targetAlpha
          }
        })
        particles = particles.filter((p) => p.targetAlpha > 0 || p.alpha > 0.02)
      }

      const draw = () => {
        ctx.clearRect(0, 0, width, height)
        for (const p of particles) {
          if (p.alpha < 0.02) continue
          ctx.globalAlpha = p.alpha
          ctx.fillStyle = p.color
          ctx.fillRect(p.x, p.y, particleSize, particleSize)
        }
        ctx.globalAlpha = 1
      }

      const step = () => {
        raf = 0
        const r2 = repelRadius * repelRadius
        let energy = 0
        for (const p of particles) {
          // Spring toward the target, then damp
          p.vx += (p.tx - p.x) * 0.045
          p.vy += (p.ty - p.y) * 0.045
          if (repelRadius > 0) {
            const dx = p.x - pointer.x
            const dy = p.y - pointer.y
            const d2 = dx * dx + dy * dy
            if (d2 < r2 && d2 > 0.01) {
              const force = (1 - d2 / r2) * 6
              const d = Math.sqrt(d2)
              p.vx += (dx / d) * force
              p.vy += (dy / d) * force
            }
          }
          p.vx *= 0.82
          p.vy *= 0.82
          p.x += p.vx
          p.y += p.vy
          p.alpha += (p.targetAlpha - p.alpha) * 0.08
          energy +=
            Math.abs(p.vx) +
            Math.abs(p.vy) +
            Math.abs(p.tx - p.x) +
            Math.abs(p.ty - p.y) +
            Math.abs(p.targetAlpha - p.alpha)
        }
        draw()
        // Sleep once every particle has settled; a morph, the cursor or
        // coming back on screen wakes it
        if (visible && energy > particles.length * 0.02) {
          raf = requestAnimationFrame(step)
        }
      }

      const start = () => {
        if (raf || reduceMotion) return
        raf = requestAnimationFrame(step)
      }
      const stop = () => {
        cancelAnimationFrame(raf)
        raf = 0
      }

      const resize = () => {
        const rect = wrap.getBoundingClientRect()
        const dpr = Math.min(window.devicePixelRatio || 1, 2)
        width = Math.max(1, Math.round(rect.width))
        height = Math.max(1, Math.round(rect.height))
        canvas.width = width * dpr
        canvas.height = height * dpr
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
        colorCache.clear()
        morphTo(wordIndex, particles.length === 0)
        if (reduceMotion) draw()
        else start()
      }

      const resizeObserver = new ResizeObserver(resize)
      resizeObserver.observe(wrap)

      // Animate only while on screen
      const io = new IntersectionObserver(([entry]) => {
        visible = entry.isIntersecting
        if (visible) start()
        else stop()
      })
      io.observe(wrap)

      if (words.length > 1) {
        timer = setInterval(() => {
          if (!visible && !reduceMotion) return
          wordIndex = (wordIndex + 1) % words.length
          morphTo(wordIndex, false)
          if (reduceMotion) draw()
          else start()
        }, interval)
      }

      const onMove = (e: PointerEvent) => {
        const rect = canvas.getBoundingClientRect()
        // Scaled containers: map screen pixels back to canvas pixels
        pointer.x = ((e.clientX - rect.left) / rect.width) * width
        pointer.y = ((e.clientY - rect.top) / rect.height) * height
        start()
      }
      const onLeave = () => {
        pointer.x = -9999
        pointer.y = -9999
        start()
      }
      wrap.addEventListener("pointermove", onMove)
      wrap.addEventListener("pointerleave", onLeave)

      return () => {
        stop()
        clearInterval(timer)
        themeObserver.disconnect()
        scheme.removeEventListener("change", onTheme)
        resizeObserver.disconnect()
        io.disconnect()
        wrap.removeEventListener("pointermove", onMove)
        wrap.removeEventListener("pointerleave", onLeave)
      }
      // words and colors are compared through their keys
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
      wordsKey,
      colorsKey,
      interval,
      density,
      particleSize,
      repelRadius,
      fontWeight,
    ])

    return (
      <div
        ref={wrapRef}
        role="img"
        aria-label={label ?? words.join(", ")}
        className={cn(
          "relative h-48 w-full touch-pan-y select-none",
          className
        )}
        {...props}
      >
        <canvas
          ref={canvasRef}
          aria-hidden="true"
          className="absolute inset-0 size-full"
        />
      </div>
    )
  }
)
ParticleText.displayName = "ParticleText"

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `words` | `string[]` | - | Yes | Words to cycle through. Short words read best. |
| `interval` | `number` | `3200` | No | Milliseconds each word stays before morphing. |
| `colors` | `string[]` | `Deep cyan → violet → pink in light mode, bright in dark mode` | No | Gradient across the text, left to right. The default switches with the theme. |
| `density` | `number` | `4` | No | Distance between particles in px; smaller is denser and heavier. |
| `particleSize` | `number` | `2.5` | No | Particle size in px. |
| `repelRadius` | `number` | `90` | No | How far the cursor pushes particles, in px. 0 turns it off. |
| `fontWeight` | `number` | `800` | No | Weight of the font the words are sampled from. The font family is inherited. |
| `label` | `string` | - | No | Accessible text. Defaults to the words joined with commas. |
| `className` | `string` | - | No | Extra classes for the canvas wrapper (set its height here; default h-48). |
| `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | No | Any other attributes, passed to the canvas wrapper (set its height here; default h-48). |

## Usage
```tsx
"use client"

import { ParticleText } from "@/components/ui/particle-text"

export default function ParticleTextDemo() {
  return (
    <div className="flex w-full max-w-3xl flex-col items-center gap-4 px-6 py-12">
      <ParticleText
        words={["DESIGN", "BUILD", "LAUNCH"]}
        className="h-40 sm:h-56"
      />
      <p className="text-sm text-muted-foreground">
        Move your cursor through the letters
      </p>
    </div>
  )
}

```
