# Gravity Dots
*URL: https://www.grettech.com/components/gravity-dots*

A dot-grid background that bends toward the cursor like a gravity well. Click to send a glowing shockwave through it.

- Dots are pulled toward the cursor and glow as they near it
- Clicks send an expanding shockwave
- Follows light and dark mode, redrawing when the theme switches
- Sleeps when idle and off screen to save battery
- Works inside scaled containers; ignores touch scrolling

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/gravity-dots
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/gravity-dots-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/gravity-dots.tsx`
```tsx
"use client"

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

export interface GravityDotsProps extends React.HTMLAttributes<HTMLDivElement> {
  /** Content shown over the dots */
  children?: React.ReactNode
  /** Distance between dots in px */
  gap?: number
  /** Dot radius in px */
  dotSize?: number
  /** Resting dot colour. Defaults to the text colour at low opacity, so it
   * follows light and dark mode. */
  color?: string
  /** Colour dots glow near the cursor and in shockwaves */
  glowColor?: string
  /** Reach of the cursor's pull in px */
  radius?: number
  /** How far dots are pulled toward the cursor, 0–1 */
  strength?: number
  /** Clicking sends a shockwave through the field */
  shockwave?: boolean
}

type Dot = {
  ox: number
  oy: number
  x: number
  y: number
  vx: number
  vy: number
  heat: number
}
type Wave = { x: number; y: number; r: number }

const WAVE_SPEED = 9
const WAVE_WIDTH = 60

export const GravityDots = React.forwardRef<HTMLDivElement, GravityDotsProps>(
  (
    {
      children,
      gap = 24,
      dotSize = 1.6,
      color,
      glowColor = "#0ea5e9",
      radius = 170,
      strength = 0.32,
      shockwave = true,
      className,
      ...props
    },
    forwardedRef
  ) => {
    const wrapRef = React.useRef<HTMLDivElement>(null)
    React.useImperativeHandle(forwardedRef, () => wrapRef.current!)
    const canvasRef = React.useRef<HTMLCanvasElement>(null)

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

      let width = 0
      let height = 0
      let dots: Dot[] = []
      let waves: Wave[] = []
      let pointer: { x: number; y: number } | null = null
      let raf = 0
      let visible = true

      // Without a color prop, dots use the current text colour (theme-aware)
      let restColor = color ?? "currentColor"
      const restAlpha = color ? 1 : 0.28
      const readColors = () => {
        if (!color) restColor = getComputedStyle(canvas).color
      }
      readColors()

      const draw = () => {
        ctx.clearRect(0, 0, width, height)
        ctx.fillStyle = restColor
        ctx.globalAlpha = restAlpha
        ctx.beginPath()
        for (const d of dots) {
          if (d.heat > 0.02) continue
          ctx.moveTo(d.x + dotSize, d.y)
          ctx.arc(d.x, d.y, dotSize, 0, Math.PI * 2)
        }
        ctx.fill()
        ctx.globalAlpha = 1
        // Hot dots: brighter, larger, glowing
        ctx.fillStyle = glowColor
        ctx.shadowColor = glowColor
        ctx.shadowBlur = 8
        for (const d of dots) {
          if (d.heat <= 0.02) continue
          ctx.globalAlpha = Math.min(1, 0.25 + d.heat)
          ctx.beginPath()
          ctx.arc(d.x, d.y, dotSize * (1 + d.heat * 1.2), 0, Math.PI * 2)
          ctx.fill()
        }
        ctx.globalAlpha = 1
        ctx.shadowBlur = 0
      }

      const step = () => {
        raf = 0
        const r2 = radius * radius
        let energy = 0
        for (const w of waves) w.r += WAVE_SPEED
        waves = waves.filter((w) => w.r < Math.hypot(width, height))

        for (const d of dots) {
          let tx = d.ox
          let ty = d.oy
          let heat = 0
          if (pointer) {
            const dx = pointer.x - d.ox
            const dy = pointer.y - d.oy
            const dist2 = dx * dx + dy * dy
            if (dist2 < r2) {
              const f = (1 - Math.sqrt(dist2) / radius) ** 2
              tx += dx * strength * f
              ty += dy * strength * f
              heat = f
            }
          }
          for (const w of waves) {
            const dx = d.ox - w.x
            const dy = d.oy - w.y
            const dist = Math.hypot(dx, dy) || 1
            const band = 1 - Math.abs(dist - w.r) / WAVE_WIDTH
            if (band > 0) {
              const fade = Math.max(0, 1 - w.r / 900)
              tx += (dx / dist) * band * 18 * fade
              ty += (dy / dist) * band * 18 * fade
              heat = Math.max(heat, band * fade)
            }
          }
          d.vx = (d.vx + (tx - d.x) * 0.12) * 0.78
          d.vy = (d.vy + (ty - d.y) * 0.12) * 0.78
          d.x += d.vx
          d.y += d.vy
          d.heat += (heat - d.heat) * 0.2
          energy += Math.abs(d.vx) + Math.abs(d.vy) + d.heat
        }
        draw()
        // Sleep once everything has settled; input wakes it again
        if (visible && (energy > 0.5 || waves.length > 0 || pointer)) {
          raf = requestAnimationFrame(step)
        }
      }
      const wake = () => {
        if (!raf && visible && !reduceMotion) raf = requestAnimationFrame(step)
      }

      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)
        dots = []
        const offsetX = (width % gap) / 2
        const offsetY = (height % gap) / 2
        for (let y = offsetY; y <= height; y += gap) {
          for (let x = offsetX; x <= width; x += gap) {
            dots.push({ ox: x, oy: y, x, y, vx: 0, vy: 0, heat: 0 })
          }
        }
        draw()
      }
      const resizeObserver = new ResizeObserver(resize)
      resizeObserver.observe(wrap)

      const io = new IntersectionObserver(([entry]) => {
        visible = entry.isIntersecting
        if (visible) wake()
      })
      io.observe(wrap)

      // Redraw in the new colours when the theme switches
      const onTheme = () => {
        readColors()
        draw()
      }
      const themeObserver = new MutationObserver(onTheme)
      themeObserver.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ["class", "style", "data-theme"],
      })
      const scheme = window.matchMedia("(prefers-color-scheme: dark)")
      scheme.addEventListener("change", onTheme)

      const local = (e: PointerEvent) => {
        const rect = canvas.getBoundingClientRect()
        // Scaled containers: map screen pixels back to canvas pixels
        return {
          x: ((e.clientX - rect.left) / rect.width) * width,
          y: ((e.clientY - rect.top) / rect.height) * height,
        }
      }
      const onMove = (e: PointerEvent) => {
        if (e.pointerType === "touch") return
        pointer = local(e)
        wake()
      }
      const onLeave = () => {
        pointer = null
        wake()
      }
      const onDown = (e: PointerEvent) => {
        if (!shockwave) return
        waves.push({ ...local(e), r: 0 })
        wake()
      }
      wrap.addEventListener("pointermove", onMove)
      wrap.addEventListener("pointerleave", onLeave)
      wrap.addEventListener("pointerdown", onDown)

      return () => {
        cancelAnimationFrame(raf)
        resizeObserver.disconnect()
        io.disconnect()
        themeObserver.disconnect()
        scheme.removeEventListener("change", onTheme)
        wrap.removeEventListener("pointermove", onMove)
        wrap.removeEventListener("pointerleave", onLeave)
        wrap.removeEventListener("pointerdown", onDown)
      }
    }, [gap, dotSize, color, glowColor, radius, strength, shockwave])

    return (
      <div
        ref={wrapRef}
        className={cn(
          "relative isolate min-h-64 w-full overflow-hidden",
          className
        )}
        {...props}
      >
        <canvas
          ref={canvasRef}
          aria-hidden="true"
          className="absolute inset-0 -z-10 size-full text-foreground"
        />
        {children}
      </div>
    )
  }
)
GravityDots.displayName = "GravityDots"

```

**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 |
|---|---|---|---|---|
| `children` | `React.ReactNode` | - | No | Content shown over the dots. |
| `gap` | `number` | `24` | No | Distance between dots in px. |
| `dotSize` | `number` | `1.6` | No | Dot radius in px. |
| `color` | `string` | `Text colour at 28% opacity` | No | Resting dot colour. By default the dots use the text colour at low opacity, so they follow light and dark mode. |
| `glowColor` | `string` | `"#0ea5e9"` | No | Colour of dots near the cursor and in shockwaves. |
| `radius` | `number` | `170` | No | Reach of the cursor's pull in px. |
| `strength` | `number` | `0.32` | No | How far dots move toward the cursor, 0–1. |
| `shockwave` | `boolean` | `true` | No | Clicking sends a shockwave. |
| `className` | `string` | - | No | Extra classes for the root element (transparent by default; set a background here). |
| `...props` | `React.HTMLAttributes<HTMLDivElement>` | - | No | Any other attributes, passed to the root element (transparent by default; set a background here). |

## Usage
```tsx
"use client"

import { GravityDots } from "@/components/ui/gravity-dots"

export default function GravityDotsDemo() {
  return (
    <GravityDots className="flex h-[420px] items-center justify-center rounded-3xl border bg-background">
      <div className="pointer-events-none px-6 text-center">
        <h2 className="text-4xl font-bold tracking-tight text-foreground sm:text-5xl">
          Everything orbits
          <br />
          <span className="text-sky-500 dark:text-sky-400">your product</span>
        </h2>
        <p className="mt-4 text-sm text-muted-foreground">
          Move to pull the field. Click to send a shockwave.
        </p>
      </div>
    </GravityDots>
  )
}

```
