# SVG Filters

SVG Filters is a heavy word whose outlines keep melting and flowing under noise and a wave.

- Live demo: https://dmivanov.ru/experiments/svg-filters
- Original CodePen: https://codepen.io/divulture/pen/YPyMELv

## 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 `svg-filters.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="svg-filters" style="position: relative; width: 100%; height: 480px;"></div>
   ```

3. Mount the effect from a module script:

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

     const effect = mount(document.getElementById("svg-filters"), { ...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 | `"SUPERSOLID"` | text, up to 12 chars |
| `noiseScale` | Noise scale | `42` | 0–140 |
| `noiseFreq` | Noise frequency | `12` | 2–60 |
| `seed` | Seed | `2` | 0–100 |
| `motion` | Motion | `2.5` | 0–6 |
| `waveScale` | Wave scale | `12` | 0–80 |
| `waveFreq` | Wave frequency | `8` | 1–30 |
| `textColor` | Text 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));
}
```

## svg-filters.js

```js
import { injectStyle, loadFonts, safeArea, uniqueId, watchSize } from "./shared.js";

export const meta = {
  slug: "svg-filters",
  description: "SVG Filters is a heavy word whose outlines keep melting and flowing under noise and a wave.",
  title: "SVG Filters",
  codepen: "https://codepen.io/divulture/pen/YPyMELv",
  replay: false,
  fonts: [{ family: "Inter", weight: "900", href: "https://fonts.googleapis.com/css2?family=Inter:wght@900&display=swap" }],
  controls: [
    { key: "text", label: "Text", type: "text", maxlength: 12, uppercase: true },
    { key: "noiseScale", label: "Noise scale", type: "range", min: 0, max: 140, step: 1, unit: "" },
    { key: "noiseFreq", label: "Noise frequency", type: "range", min: 2, max: 60, step: 1, unit: "" },
    { key: "seed", label: "Seed", type: "range", min: 0, max: 100, step: 1, unit: "" },
    { key: "motion", label: "Motion", type: "range", min: 0, max: 6, step: 0.5, unit: "" },
    { key: "waveScale", label: "Wave scale", type: "range", min: 0, max: 80, step: 1, unit: "" },
    { key: "waveFreq", label: "Wave frequency", type: "range", min: 1, max: 30, step: 1, unit: "" },
    { key: "textColor", label: "Text color", type: "color" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    text: "SUPERSOLID",
    noiseScale: 42,
    noiseFreq: 12,
    seed: 2,
    motion: 2.5,
    waveScale: 12,
    waveFreq: 8,
    textColor: "#e6edf2",
    background: "#171717"
  }
};

const CSS = `
.fx-svg-filters { position: absolute; inset: 0; display: grid; place-items: center; overflow: hidden; background: var(--fx-bg); }
.fx-svg-filters svg { display: block; width: 100%; height: 100%; }
`;

const SVG_NS = "http://www.w3.org/2000/svg";

export function mount(stage, initialSettings, { mode = "live", preview = false } = {}) {
  injectStyle("fx-svg-filters-style", CSS);
  let settings = { ...meta.defaults, ...initialSettings };
  const filterId = uniqueId("fx-warp");
  const root = document.createElement("div");
  root.className = "fx-svg-filters";
  // Turbulence noise morphs the letters; a second, stretched noise adds a wave.
  root.innerHTML = `
    <svg viewBox="0 0 1600 600" xmlns="${SVG_NS}" aria-hidden="true" focusable="false">
      <defs>
        <filter id="${filterId}" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB">
          <feTurbulence data-role="turb" type="turbulence" numOctaves="2" result="noise" />
          <feDisplacementMap data-role="disp" in="SourceGraphic" in2="noise" xChannelSelector="R" yChannelSelector="G" result="morph" />
          <feTurbulence data-role="waveTurb" type="turbulence" numOctaves="1" seed="5" result="waveMap" />
          <feDisplacementMap data-role="waveDisp" in="morph" in2="waveMap" xChannelSelector="R" yChannelSelector="G" />
        </filter>
      </defs>
      <text x="800" y="320" filter="url(#${filterId})" font-family="Inter, sans-serif" font-weight="900" font-size="210" text-anchor="middle" dominant-baseline="middle" letter-spacing="10"></text>
    </svg>`;
  stage.append(root);
  const node = (role) => root.querySelector(`[data-role="${role}"]`);
  const turb = node("turb");
  const disp = node("disp");
  const waveTurb = node("waveTurb");
  const waveDisp = node("waveDisp");
  const label = root.querySelector("text");
  const svg = root.querySelector("svg");
  let frame = 0;

  function render() {
    root.style.setProperty("--fx-bg", settings.background);
    label.setAttribute("fill", settings.textColor);
    label.textContent = settings.text;
    disp.setAttribute("scale", settings.noiseScale);
    turb.setAttribute("seed", settings.seed);
    turb.setAttribute("baseFrequency", (settings.noiseFreq / 1000).toFixed(3));
    waveDisp.setAttribute("scale", settings.waveScale);
    waveTurb.setAttribute("baseFrequency", `${(settings.waveFreq / 1000).toFixed(3)} 0`);
    frame_();
  }

  // Frame the word: the viewBox matches the stage and puts the text inside
  // the shared safe area.
  function frame_() {
    const box = label.getBBox();
    const width = root.clientWidth;
    const height = root.clientHeight;
    if (!box.width || !width || !height) return;
    const area = safeArea(root);
    const scale = Math.min(area.width / box.width, area.height / box.height);
    const viewWidth = width / scale;
    const viewHeight = height / scale;
    const cx = box.x + box.width / 2;
    const cy = box.y + box.height / 2;
    svg.setAttribute("viewBox", `${cx - viewWidth / 2} ${cy - viewHeight / 2} ${viewWidth} ${viewHeight}`);
  }

  function tick(now) {
    const base = settings.noiseFreq / 1000;
    turb.setAttribute("baseFrequency", (base + (settings.motion / 1000) * Math.sin((now / 1000) * 2.2)).toFixed(4));
    const wave = settings.waveFreq / 1000 + 0.0015 * Math.sin(now / 400);
    waveTurb.setAttribute("baseFrequency", `${wave.toFixed(4)} 0`);
    frame = requestAnimationFrame(tick);
  }

  render();
  const stopWatching = watchSize(stage, frame_);
  loadFonts(meta.fonts).then(frame_);
  if (mode === "live") frame = requestAnimationFrame(tick);

  return {
    update(next) {
      settings = { ...settings, ...next };
      render();
    },
    replay() {},
    destroy() {
      cancelAnimationFrame(frame);
      stopWatching();
      root.remove();
    }
  };
}
```
