# Particles Interaction

Particles Interaction is a word made of thousands of particles. The cursor scatters them, and a moment later they gather back into letters.

- Live demo: https://dmivanov.ru/experiments/particles
- Original CodePen: https://codepen.io/divulture/pen/wBvWmav

## How to embed

Instructions for an AI agent or developer adding this effect to a website.

1. Save the two code blocks below as `shared.js` and `particles.js` in the same folder of the project's scripts. They are plain ES modules with no build step and no dependencies.
2. Add a container with an explicit size where the effect should appear. The effect fills it completely:

   ```html
   <div id="particles" style="position: relative; width: 100%; height: 480px;"></div>
   ```

3. Mount the effect from a module script:

   ```html
   <script type="module">
     import { mount, meta } from "./particles.js";

     const effect = mount(document.getElementById("particles"), { ...meta.defaults });
     // effect.update({ ... }) changes parameters at runtime.
     // effect.replay() restarts one-shot animations.
     // effect.destroy() removes the effect and its listeners.
   </script>
   ```

The module injects its own CSS and loads its Google Font. Pixel values are authored for a 1000px-wide container and scale with the container width. In React, Vue or Svelte, call `mount` when the component mounts and `destroy` when it unmounts. Pass `{ mode: "still" }` as the third argument of `mount` to render a single static frame, for example for a preview card.

## Parameters

| Key | Control | Default | Values |
| --- | --- | --- | --- |
| `text` | Text | `"Particles"` | text, up to 14 chars |
| `size` | Size | `200` | 80–320 px |
| `density` | Density | `4` | 2–10 px |
| `radius` | Radius | `64` | 24–160 px |
| `recovery` | Recovery | `1` | 1–10 |
| `textColor` | Particle color | `"#e6edf2"` | hex color |
| `background` | Background | `"#171717"` | hex color |

## shared.js

```js
// Shared helpers for experiment modules.
//
// Every experiment exports `meta` (title, controls, defaults) and
// `mount(stage, settings, { mode })`. The stage is any positioned element; the
// effect fills it and scales its pixel values to the stage width, so the same
// code runs in the full demo, in small card previews, and on a client's site.
// `mode` is "live" (interactive / animated) or "still" (one static frame).

export const REFERENCE_WIDTH = 1000;

const fontRequests = new Map();

// Loads a Google Fonts stylesheet once and resolves when the family is ready.
export function loadFont(href, family, weight = "400") {
  if (!href || typeof document === "undefined") return Promise.resolve();
  const key = `${family}:${weight}`;
  if (fontRequests.has(key)) return fontRequests.get(key);
  // The @font-face rules exist only after the stylesheet loads, so wait for
  // it before asking the browser to fetch the font itself.
  let link = document.querySelector(`link[href="${href}"]`);
  const stylesheet = link && link.sheet ? Promise.resolve() : new Promise((resolve) => {
    if (!link) {
      link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = href;
      document.head.append(link);
    }
    link.addEventListener("load", resolve, { once: true });
    link.addEventListener("error", resolve, { once: true });
  });
  const request = stylesheet
    .then(() => (document.fonts ? document.fonts.load(`${weight} 32px "${family}"`) : null))
    .catch(() => {})
    .then(() => undefined);
  fontRequests.set(key, request);
  return request;
}

export function loadFonts(fonts = []) {
  return Promise.all(fonts.map((font) => loadFont(font.href, font.family, font.weight)));
}

// Adds a stylesheet for an effect once per document.
export function injectStyle(id, css) {
  if (typeof document === "undefined" || document.getElementById(id)) return;
  const style = document.createElement("style");
  style.id = id;
  style.textContent = css;
  document.head.append(style);
}

// Pixel values in settings are authored for a 1000px-wide stage.
export function stageUnit(stage) {
  return (stage.clientWidth || REFERENCE_WIDTH) / REFERENCE_WIDTH;
}

// Every effect keeps the same margin inside its stage: 8% of the stage width.
export const SAFE_AREA = 0.08;

export function safeArea(stage) {
  const pad = Math.round(stage.clientWidth * SAFE_AREA);
  return {
    pad,
    width: Math.max(1, stage.clientWidth - pad * 2),
    height: Math.max(1, stage.clientHeight - pad * 2)
  };
}

// Scale that fits a box of the given size into the safe area. Previews pass
// `grow` so every card fills its safe area the same way; the full demo only
// shrinks content that would otherwise overflow. `fill` lets a preview whose
// type reads heavy take less of the area than the others.
export function fitScale(stage, width, height, { grow = false, fill = 1 } = {}) {
  if (!width || !height) return 1;
  const area = safeArea(stage);
  const scale = Math.min(area.width / width, area.height / height);
  return grow ? scale * fill : Math.min(1, scale);
}

// Fits an element by its layout size (transforms do not affect offset sizes)
// and writes the result to its `--fx-fit` custom property.
export function fitElement(stage, element, options) {
  const scale = fitScale(stage, element.offsetWidth, element.offsetHeight, options);
  element.style.setProperty("--fx-fit", scale.toFixed(4));
  return scale;
}

export function watchSize(stage, callback) {
  if (typeof ResizeObserver === "undefined") return () => {};
  let width = stage.clientWidth;
  let height = stage.clientHeight;
  const observer = new ResizeObserver(() => {
    if (stage.clientWidth === width && stage.clientHeight === height) return;
    width = stage.clientWidth;
    height = stage.clientHeight;
    callback();
  });
  observer.observe(stage);
  return () => observer.disconnect();
}

export function localPoint(stage, event) {
  const rect = stage.getBoundingClientRect();
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}

let uid = 0;
export function uniqueId(prefix) {
  uid += 1;
  return `${prefix}-${uid}`;
}

// Splits text into words and letters without touching the original string.
export function splitWords(text) {
  return String(text).trim().split(/\s+/).filter(Boolean);
}

export function isHexColor(value) {
  return /^#[0-9a-f]{6}$/i.test(String(value));
}
```

## particles.js

```js
import { fitScale, injectStyle, loadFonts, localPoint, stageUnit, watchSize } from "./shared.js";

export const meta = {
  slug: "particles",
  description: "Particles Interaction is a word made of thousands of particles. The cursor scatters them, and a moment later they gather back into letters.",
  title: "Particles Interaction",
  codepen: "https://codepen.io/divulture/pen/wBvWmav",
  replay: false,
  fonts: [{ family: "Outfit", href: "https://fonts.googleapis.com/css2?family=Outfit&display=swap" }],
  controls: [
    { key: "text", label: "Text", type: "text", maxlength: 14 },
    { key: "size", label: "Size", type: "range", min: 80, max: 320, step: 4, unit: "px" },
    { key: "density", label: "Density", type: "range", min: 2, max: 10, step: 1, unit: "px" },
    { key: "radius", label: "Radius", type: "range", min: 24, max: 160, step: 4, unit: "px" },
    { key: "recovery", label: "Recovery", type: "range", min: 1, max: 10, step: 1, unit: "" },
    { key: "textColor", label: "Particle color", type: "color" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    text: "Particles",
    size: 200,
    density: 4,
    radius: 64,
    recovery: 1,
    textColor: "#e6edf2",
    background: "#171717"
  }
};

const CSS = `
.fx-particles { position: absolute; inset: 0; overflow: hidden; background: var(--fx-bg); cursor: none; touch-action: none; }
.fx-particles canvas { display: block; width: 100%; height: 100%; }
.fx-particles__cursor { position: absolute; top: 0; left: 0; border-radius: 50%; background: var(--fx-fg); pointer-events: none; opacity: 0; transform: translate(-50%, -50%); transition: opacity .2s ease; }
.fx-particles[data-pointer="true"] .fx-particles__cursor { opacity: 1; }
`;

const EASE = 0.2;

export function mount(stage, initialSettings, { mode = "live", preview = false } = {}) {
  injectStyle("fx-particles-style", CSS);
  let settings = { ...meta.defaults, ...initialSettings };
  const root = document.createElement("div");
  root.className = "fx-particles";
  const canvas = document.createElement("canvas");
  const cursor = document.createElement("span");
  cursor.className = "fx-particles__cursor";
  root.append(canvas, cursor);
  stage.append(root);
  const ctx = canvas.getContext("2d");

  let particles = [];
  let pointer = { x: -9999, y: -9999 };
  let frame = 0;
  let idleTimer = 0;
  let width = 0;
  let height = 0;

  function sample() {
    const unit = stageUnit(stage);
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    width = root.clientWidth;
    height = root.clientHeight;
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    root.style.setProperty("--fx-bg", settings.background);
    root.style.setProperty("--fx-fg", settings.textColor);
    cursor.style.width = cursor.style.height = `${settings.radius * unit}px`;

    // Draw the text once, then keep one particle per filled grid step.
    let fontSize = settings.size * unit;
    ctx.font = `${fontSize}px Outfit`;
    const metrics = ctx.measureText(settings.text);
    fontSize *= fitScale(stage, metrics.width, metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent, { grow: preview });
    ctx.clearRect(0, 0, width, height);
    ctx.font = `${fontSize}px Outfit`;
    ctx.fillStyle = "#fff";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(settings.text, width / 2, height / 2);
    const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
    ctx.clearRect(0, 0, width, height);

    const step = Math.max(2, Math.round(settings.density * unit * dpr));
    particles = [];
    for (let y = 0; y < image.height; y += step) {
      for (let x = 0; x < image.width; x += step) {
        if (image.data[(x + y * image.width) * 4 + 3] > 128) {
          particles.push({ x: x / dpr, y: y / dpr, ox: x / dpr, oy: y / dpr, vx: Math.random() * 4 - 2, vy: Math.random() * 4 - 2, broken: false });
        }
      }
    }
  }

  function draw(still = false) {
    const unit = stageUnit(stage);
    const reach = (settings.radius * unit) / 2;
    const recovery = 0.005 * settings.recovery;
    ctx.clearRect(0, 0, width, height);
    ctx.fillStyle = settings.textColor;
    const dot = Math.max(1, 1.6 * unit);
    for (const p of particles) {
      if (!still) {
        p.x += p.vx;
        p.y += p.vy;
        if (Math.hypot(p.x - pointer.x, p.y - pointer.y) < reach) p.broken = true;
        const ease = p.broken ? recovery : EASE;
        p.x += (p.ox - p.x) * ease;
        p.y += (p.oy - p.y) * ease;
        if (p.broken && Math.abs(p.x - p.ox) < 1 && Math.abs(p.y - p.oy) < 1) p.broken = false;
      }
      ctx.fillRect(p.x - dot / 2, p.y - dot / 2, dot, dot);
    }
  }

  function loop() {
    draw();
    frame = requestAnimationFrame(loop);
  }

  function onMove(event) {
    pointer = localPoint(stage, event);
    cursor.style.left = `${pointer.x}px`;
    cursor.style.top = `${pointer.y}px`;
    root.dataset.pointer = "true";
    clearTimeout(idleTimer);
    idleTimer = setTimeout(() => particles.forEach((p) => { p.broken = false; }), 3000);
  }
  function onLeave() {
    pointer = { x: -9999, y: -9999 };
    root.dataset.pointer = "false";
  }

  function start() {
    sample();
    if (mode === "live") {
      cancelAnimationFrame(frame);
      loop();
    } else {
      draw(true);
    }
  }

  if (mode === "live") {
    stage.addEventListener("pointermove", onMove);
    stage.addEventListener("pointerleave", onLeave);
  }
  const stopWatching = watchSize(stage, start);
  loadFonts(meta.fonts).then(start);

  return {
    update(next) {
      settings = { ...settings, ...next };
      start();
    },
    replay() {},
    destroy() {
      cancelAnimationFrame(frame);
      clearTimeout(idleTimer);
      stage.removeEventListener("pointermove", onMove);
      stage.removeEventListener("pointerleave", onLeave);
      stopWatching();
      root.remove();
    }
  };
}
```
