# Paint Reveal

Paint Reveal is an interactive animation where cursor or touch movement leaves a fluid trace across typography.

- Live demo: https://dmivanov.ru/experiments/paint-reveal

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

3. Mount the effect from a module script:

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

     const effect = mount(document.getElementById("paint-reveal"), { ...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 |
| --- | --- | --- | --- |
| `brushSize` | Brush size | `4.6` | 2–12 px |
| `turbulence` | Turbulence | `0.11` | 0–0.32 |
| `fade` | Fade | `0.97` | 0.94–0.995 |
| `background` | Background | `"#efe8d8"` | 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));
}
```

## paint-reveal.js

```js
import { watchSize } from "./shared.js";

export const meta = {
  slug: "paint-reveal",
  title: "Paint Reveal",
  description: "Paint Reveal is an interactive animation where cursor or touch movement leaves a fluid trace across typography.",
  codepen: "",
  replay: false,
  fonts: [],
  controls: [
    { key: "brushSize", label: "Brush size", type: "range", min: 2, max: 12, step: 0.2, unit: "px" },
    { key: "turbulence", label: "Turbulence", type: "range", min: 0, max: 0.32, step: 0.01 },
    { key: "fade", label: "Fade", type: "range", min: 0.94, max: 0.995, step: 0.001 },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    brushSize: 4.6,
    turbulence: 0.11,
    fade: 0.97,
    background: "#efe8d8"
  }
};

const CSS = `
.fx-paint-reveal { position: absolute; inset: 0; overflow: hidden; background: #efe8d8; }
.fx-paint-reveal__frame { display: block; width: 100%; height: 100%; border: 0; background: #efe8d8; }
.fx-paint-reveal--preview { cursor: pointer; }
.fx-paint-reveal--still { display: grid; place-items: center; }
.fx-paint-reveal img.fx-paint-reveal__still-image { display: block; width: 76%; height: 76%; object-fit: contain; filter: none; transform: none; }
.fx-paint-reveal--preview .fx-paint-reveal__frame { pointer-events: none; }
.fx-paint-reveal--preview-loading .fx-paint-reveal__frame { opacity: 0; }
.fx-paint-reveal--preview-loading .fx-paint-reveal__still-image { position: absolute; inset: 12%; width: 76%; height: 76%; }
`;

export function mount(stage, initialSettings, { mode = "live", preview = false } = {}) {
  const styleId = "fx-paint-reveal-style";
  if (!document.getElementById(styleId)) {
    const style = document.createElement("style");
    style.id = styleId;
    style.textContent = CSS;
    document.head.append(style);
  }

  let settings = { ...meta.defaults, ...initialSettings };
  const root = document.createElement("div");
  root.className = "fx-paint-reveal";

  // Card previews should always have a finished first frame. Loading the full
  // canvas scene here left a blank tile until its image layers were ready.
  if (mode === "still") {
    root.classList.add("fx-paint-reveal--still");
    root.style.background = settings.background;
    const image = document.createElement("img");
    image.className = "fx-paint-reveal__still-image";
    image.src = "/experiments/paint-reveal/paint-top.webp";
    image.alt = "";
    image.draggable = false;
    root.append(image);
    stage.append(root);
    return {
      update(next) {
        settings = { ...settings, ...next };
        root.style.background = settings.background;
      },
      replay() {},
      destroy() { root.remove(); }
    };
  }

  const frame = document.createElement("iframe");
  frame.className = "fx-paint-reveal__frame";
  frame.src = "/experiments/paint-reveal/scene.html";
  let poster = null;
  if (preview) {
    root.classList.add("fx-paint-reveal--preview", "fx-paint-reveal--preview-loading");
    frame.setAttribute("aria-hidden", "true");
    poster = document.createElement("img");
    poster.className = "fx-paint-reveal__still-image";
    poster.src = "/experiments/paint-reveal/paint-top.webp";
    poster.alt = "";
    poster.draggable = false;
    root.append(poster);
  }
  else {
    frame.title = "Paint reveal interaction";
    frame.setAttribute("aria-label", "Paint reveal interaction");
  }
  root.append(frame);
  stage.append(root);

  function sync() {
    if (!frame.contentWindow) return;
    frame.contentWindow.postMessage({ type: "paint-reveal-settings", settings }, window.location.origin);
  }

  let pointerForwarded = false;
  const forwardPointer = (phase, event) => {
    if (!preview || !frame.contentWindow) return;
    const rect = stage.getBoundingClientRect();
    frame.contentWindow.postMessage({
      type: "paint-reveal-pointer",
      phase,
      x: event ? (event.clientX - rect.left) / rect.width : 0,
      y: event ? (event.clientY - rect.top) / rect.height : 0
    }, window.location.origin);
  };
  const onPreviewPointerMove = (event) => {
    if (!pointerForwarded) {
      forwardPointer("enter", event);
      pointerForwarded = true;
    }
    forwardPointer("move", event);
  };
  const onPreviewPointerLeave = () => {
    forwardPointer("leave");
    pointerForwarded = false;
  };
  const onLoad = () => {
    sync();
  };
  frame.addEventListener("load", onLoad);
  if (preview) {
    stage.addEventListener("pointermove", onPreviewPointerMove);
    stage.addEventListener("pointerleave", onPreviewPointerLeave);
  }
  const onSceneReady = (event) => {
    if (event.origin !== window.location.origin || event.source !== frame.contentWindow || event.data?.type !== "paint-reveal-ready") return;
    root.classList.remove("fx-paint-reveal--preview-loading");
    if (poster) poster.remove();
    poster = null;
  };
  window.addEventListener("message", onSceneReady);
  const stopWatching = watchSize(stage, () => {
    // The iframe receives its own resize event; a fresh settings message keeps
    // its canvas background in sync after a responsive layout change.
    sync();
  });

  return {
    update(next) {
      settings = { ...settings, ...next };
      sync();
    },
    replay() {},
    destroy() {
      stopWatching();
      stage.removeEventListener("pointermove", onPreviewPointerMove);
      stage.removeEventListener("pointerleave", onPreviewPointerLeave);
      frame.removeEventListener("load", onLoad);
      window.removeEventListener("message", onSceneReady);
      root.remove();
    }
  };
}
```
