# Image Trail

Area where images, cards, or emoji pop up along the pointer path and fade, scale, spin, or pile up. Can draw its own trail while on screen.

- Category: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/image-trail.json
- CLI: `npx markasui@latest add image-trail`

## When to use

A playful hero, promo banner, team section, or call to action where the pointer should leave a visual trail of product shots, colors, emoji, or faces.

- Give the component a fixed height and a background so the trail has room
- Keep items small (48 to 96 px) and use 3 to 6 different ones
- Never put information only in the items; repeat it in the content
- Turn on autoplay for touch-first pages, and use one image trail per screen

## Code

### Blade

Save at `resources/views/components/markas/image-trail.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'threshold' => 40,
    'variant' => 'fade',
    'max' => 12,
    'duration' => 800,
    'autoplay' => false,
])

@php
    $base = 'relative isolate overflow-hidden';
    $layerClass = 'pointer-events-none absolute inset-0 -z-10 [&>*]:absolute [&>*]:-translate-x-1/2 [&>*]:-translate-y-1/2 [&>*]:opacity-0 motion-reduce:hidden';
    $dotClass = 'block size-4 rounded-full bg-primary';
    $items = $__laravel_slots['items'] ?? null;
    $options = [
        'threshold' => (float) $threshold,
        'variant' => in_array($variant, ['fade', 'scale', 'rotate', 'stack'], true) ? $variant : 'fade',
        'max' => (int) $max,
        'duration' => (float) $duration,
        'autoplay' => (bool) $autoplay,
    ];
@endphp

{{-- Clones the next item to the pointer once it has travelled `threshold` px. At most `max` clones live at once. --}}
<div
    x-data="{
        stop: null,
        frames(variant, n) {
            const turn = ((n * 47) % 70) - 35;
            if (variant === 'scale') return [{ opacity: 1, transform: 'scale(0)' }, { opacity: 1, transform: 'scale(1)', offset: 0.25 }, { opacity: 0, transform: 'scale(0.2)' }];
            if (variant === 'rotate') return [{ opacity: 0, transform: `rotate(${turn}deg) scale(.6)` }, { opacity: 1, transform: `rotate(${turn / 2}deg) scale(1)`, offset: 0.2 }, { opacity: 0, transform: 'rotate(0deg) translateY(32px) scale(.9)' }];
            if (variant === 'stack') return [{ opacity: 0, transform: `rotate(${turn / 3}deg) scale(1.4)` }, { opacity: 1, transform: `rotate(${turn / 3}deg) scale(1)` }];
            return [{ opacity: 1 }, { opacity: 0 }];
        },
        init() {
            const { threshold, variant, max, duration, autoplay } = @js($options);
            const root = this.$root;
            const source = this.$refs.source;
            const layer = this.$refs.layer;
            const still = () => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
            let last = null;
            let count = 0;
            let inside = false;
            const spawn = (x, y) => {
                const items = source.children;
                if (! items.length) return;
                if (last && Math.hypot(x - last.x, y - last.y) < threshold) return;
                last = { x, y };
                if (layer.children.length >= max) layer.firstElementChild?.remove();
                const item = items[count % items.length].cloneNode(true);
                item.style.left = `${x}px`;
                item.style.top = `${y}px`;
                layer.append(item);
                const stack = variant === 'stack';
                const animation = item.animate?.(this.frames(variant, count), { duration: stack ? duration * 0.4 : duration, easing: 'cubic-bezier(.2,.7,.3,1)', fill: 'forwards' });
                if (animation && ! stack) animation.onfinish = () => item.remove();
                count++;
            };
            const move = (event) => {
                if (still()) return;
                inside = true;
                const rect = root.getBoundingClientRect();
                spawn(event.clientX - rect.left, event.clientY - rect.top);
            };
            const leave = () => {
                inside = false;
                last = null;
                if (variant !== 'stack') return;
                for (const item of [...layer.children]) {
                    const out = item.animate?.([{ opacity: 1 }, { opacity: 0 }], { duration: 300, fill: 'forwards' });
                    if (out) out.onfinish = () => item.remove();
                    else item.remove();
                }
            };
            root.addEventListener('pointermove', move);
            root.addEventListener('pointerleave', leave);
            {{-- Autoplay: a figure-eight trail while visible, the tab is shown, and the pointer is elsewhere. --}}
            let frame = 0;
            let observer = null;
            let sync = null;
            if (autoplay && ! still() && typeof IntersectionObserver === 'function') {
                let seen = false;
                const run = (now) => {
                    if (! inside) {
                        const t = now / 1100;
                        const { width, height } = root.getBoundingClientRect();
                        spawn(width * (0.5 + 0.36 * Math.sin(t)), height * (0.5 + 0.3 * Math.sin(2 * t)));
                    }
                    frame = requestAnimationFrame(run);
                };
                sync = () => {
                    cancelAnimationFrame(frame);
                    if (seen && ! document.hidden) frame = requestAnimationFrame(run);
                };
                observer = new IntersectionObserver(([entry]) => {
                    seen = Boolean(entry?.isIntersecting);
                    sync();
                });
                observer.observe(root);
                document.addEventListener('visibilitychange', sync);
            }
            this.stop = () => {
                root.removeEventListener('pointermove', move);
                root.removeEventListener('pointerleave', leave);
                observer?.disconnect();
                if (sync) document.removeEventListener('visibilitychange', sync);
                cancelAnimationFrame(frame);
                layer.replaceChildren();
            };
        },
        destroy() {
            this.stop?.();
        },
    }"
    {{ $attributes->class([$base]) }}
>
    <div x-ref="source" hidden>
        @if ($items)
            {{ $items }}
        @else
            <span class="{{ $dotClass }}"></span>
        @endif
    </div>
    <div x-ref="layer" aria-hidden="true" class="{{ $layerClass }}"></div>
    {{ $slot }}
</div>
```

```blade
<x-markas.image-trail variant="scale" :threshold="48" class="grid h-72 place-items-center rounded-xl bg-subtle">
    <x-slot:items>
        <img src="/img/shoe-1.webp" alt="" class="w-20 rounded-lg" />
        <img src="/img/shoe-2.webp" alt="" class="w-20 rounded-lg" />
        <img src="/img/shoe-3.webp" alt="" class="w-20 rounded-lg" />
    </x-slot:items>
    <h2 class="text-2xl font-semibold">New season sneakers</h2>
</x-markas.image-trail>
```

Needs Alpine.js.

### React

Save at `src/components/markas/ImageTrail.tsx`. No extra dependencies.

```tsx
"use client";

import { useEffect, useRef, type ComponentProps, type ReactNode } from "react";

export type ImageTrailVariant = "fade" | "scale" | "rotate" | "stack";

const base = "relative isolate overflow-hidden";
const layerClass =
  "pointer-events-none absolute inset-0 -z-10 [&>*]:absolute [&>*]:-translate-x-1/2 [&>*]:-translate-y-1/2 [&>*]:opacity-0 motion-reduce:hidden";
const dotClass = "block size-4 rounded-full bg-primary";

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

type Frame = { opacity: number; transform?: string; offset?: number };

/** Keyframes per variant. The angle comes from the trail counter, so every run looks the same. */
function frames(variant: ImageTrailVariant, n: number): Frame[] {
  const turn = ((n * 47) % 70) - 35;
  if (variant === "scale")
    return [
      { opacity: 1, transform: "scale(0)" },
      { opacity: 1, transform: "scale(1)", offset: 0.25 },
      { opacity: 0, transform: "scale(0.2)" },
    ];
  if (variant === "rotate")
    return [
      { opacity: 0, transform: `rotate(${turn}deg) scale(.6)` },
      { opacity: 1, transform: `rotate(${turn / 2}deg) scale(1)`, offset: 0.2 },
      { opacity: 0, transform: "rotate(0deg) translateY(32px) scale(.9)" },
    ];
  if (variant === "stack")
    return [
      { opacity: 0, transform: `rotate(${turn / 3}deg) scale(1.4)` },
      { opacity: 1, transform: `rotate(${turn / 3}deg) scale(1)` },
    ];
  return [{ opacity: 1 }, { opacity: 0 }];
}

type TrailOptions = {
  threshold: number;
  variant: ImageTrailVariant;
  max: number;
  duration: number;
  autoplay: boolean;
};

/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
  let frame = 0;
  let seen = false;
  const run = (now: number) => {
    tick(now);
    frame = requestAnimationFrame(run);
  };
  const sync = () => {
    cancelAnimationFrame(frame);
    if (seen && !document.hidden) frame = requestAnimationFrame(run);
  };
  const observer = new IntersectionObserver(([entry]) => {
    seen = Boolean(entry?.isIntersecting);
    sync();
  });
  observer.observe(element);
  document.addEventListener("visibilitychange", sync);
  return () => {
    observer.disconnect();
    document.removeEventListener("visibilitychange", sync);
    cancelAnimationFrame(frame);
  };
}

/** Clone the next item to (x, y) once the pointer has travelled `threshold` px. At most `max` clones live at once. */
function createTrail(
  root: HTMLElement,
  source: HTMLElement,
  layer: HTMLElement,
  options: TrailOptions,
) {
  const { threshold, variant, max, duration } = options;
  let last: { x: number; y: number } | null = null;
  let count = 0;
  let inside = false;

  const spawn = (x: number, y: number) => {
    const items = source.children;
    if (!items.length) return;
    if (last && Math.hypot(x - last.x, y - last.y) < threshold) return;
    last = { x, y };
    if (layer.children.length >= max) layer.firstElementChild?.remove();
    const item = items[count % items.length]!.cloneNode(true) as HTMLElement;
    item.style.left = `${x}px`;
    item.style.top = `${y}px`;
    layer.append(item);
    const stack = variant === "stack";
    const animation = item.animate?.(frames(variant, count), {
      duration: stack ? duration * 0.4 : duration,
      easing: "cubic-bezier(.2,.7,.3,1)",
      fill: "forwards",
    });
    if (animation && !stack) animation.onfinish = () => item.remove();
    count++;
  };

  const move = (event: PointerEvent) => {
    if (still()) return;
    inside = true;
    const rect = root.getBoundingClientRect();
    spawn(event.clientX - rect.left, event.clientY - rect.top);
  };
  const leave = () => {
    inside = false;
    last = null;
    if (variant !== "stack") return;
    for (const item of [...layer.children]) {
      const out = item.animate?.([{ opacity: 1 }, { opacity: 0 }], {
        duration: 300,
        fill: "forwards",
      });
      if (out) out.onfinish = () => item.remove();
      else item.remove();
    }
  };

  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);
  const stopAuto =
    options.autoplay && !still() && typeof IntersectionObserver === "function"
      ? whileVisible(root, (now) => {
          if (inside) return;
          const t = now / 1100;
          const { width, height } = root.getBoundingClientRect();
          spawn(
            width * (0.5 + 0.36 * Math.sin(t)),
            height * (0.5 + 0.3 * Math.sin(2 * t)),
          );
        })
      : null;

  return () => {
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    stopAuto?.();
    layer.replaceChildren();
  };
}

export type ImageTrailProps = ComponentProps<"div"> & {
  /** Elements that appear along the trail, cloned in order. A small primary dot when empty. */
  items?: ReactNode;
  /** Distance in px the pointer travels before the next item appears. */
  threshold?: number;
  /** How each item enters and leaves. */
  variant?: ImageTrailVariant;
  /** Most items on screen at once. */
  max?: number;
  /** Life of one item in ms. */
  duration?: number;
  /** Draws a figure-eight trail on its own while visible and the pointer is elsewhere. */
  autoplay?: boolean;
};

export function ImageTrail({
  items,
  threshold = 40,
  variant = "fade",
  max = 12,
  duration = 800,
  autoplay = false,
  className,
  children,
  ...props
}: ImageTrailProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const sourceRef = useRef<HTMLDivElement>(null);
  const layerRef = useRef<HTMLDivElement>(null);

  useEffect(
    () =>
      createTrail(rootRef.current!, sourceRef.current!, layerRef.current!, {
        threshold,
        variant,
        max,
        duration,
        autoplay,
      }),
    [threshold, variant, max, duration, autoplay],
  );

  return (
    <div {...props} ref={rootRef} className={cx(base, className)}>
      <div ref={sourceRef} hidden>
        {items ?? <span className={dotClass}></span>}
      </div>
      <div ref={layerRef} aria-hidden="true" className={layerClass}></div>
      {children}
    </div>
  );
}
```

```tsx
import { ImageTrail } from "@/components/markas/ImageTrail";

<ImageTrail
  variant="scale"
  threshold={48}
  className="grid h-72 place-items-center rounded-xl bg-subtle"
  items={
    <>
      <img src="/img/shoe-1.webp" alt="" className="w-20 rounded-lg" />
      <img src="/img/shoe-2.webp" alt="" className="w-20 rounded-lg" />
      <img src="/img/shoe-3.webp" alt="" className="w-20 rounded-lg" />
    </>
  }
>
  <h2 className="text-2xl font-semibold">New season sneakers</h2>
</ImageTrail>;
```

### Vue

Save at `src/components/markas/ImageTrail.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";

export type ImageTrailVariant = "fade" | "scale" | "rotate" | "stack";

const props = withDefaults(
  defineProps<{
    /** Distance in px the pointer travels before the next item appears. */
    threshold?: number;
    /** How each item enters and leaves. */
    variant?: ImageTrailVariant;
    /** Most items on screen at once. */
    max?: number;
    /** Life of one item in ms. */
    duration?: number;
    /** Draws a figure-eight trail on its own while visible and the pointer is elsewhere. */
    autoplay?: boolean;
  }>(),
  {
    threshold: 40,
    variant: "fade",
    max: 12,
    duration: 800,
    autoplay: false,
  },
);

const base = "relative isolate overflow-hidden";
const layerClass =
  "pointer-events-none absolute inset-0 -z-10 [&>*]:absolute [&>*]:-translate-x-1/2 [&>*]:-translate-y-1/2 [&>*]:opacity-0 motion-reduce:hidden";
const dotClass = "block size-4 rounded-full bg-primary";

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

type Frame = { opacity: number; transform?: string; offset?: number };

/** Keyframes per variant. The angle comes from the trail counter, so every run looks the same. */
function frames(variant: ImageTrailVariant, n: number): Frame[] {
  const turn = ((n * 47) % 70) - 35;
  if (variant === "scale")
    return [
      { opacity: 1, transform: "scale(0)" },
      { opacity: 1, transform: "scale(1)", offset: 0.25 },
      { opacity: 0, transform: "scale(0.2)" },
    ];
  if (variant === "rotate")
    return [
      { opacity: 0, transform: `rotate(${turn}deg) scale(.6)` },
      { opacity: 1, transform: `rotate(${turn / 2}deg) scale(1)`, offset: 0.2 },
      { opacity: 0, transform: "rotate(0deg) translateY(32px) scale(.9)" },
    ];
  if (variant === "stack")
    return [
      { opacity: 0, transform: `rotate(${turn / 3}deg) scale(1.4)` },
      { opacity: 1, transform: `rotate(${turn / 3}deg) scale(1)` },
    ];
  return [{ opacity: 1 }, { opacity: 0 }];
}

/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
  let frame = 0;
  let seen = false;
  const run = (now: number) => {
    tick(now);
    frame = requestAnimationFrame(run);
  };
  const sync = () => {
    cancelAnimationFrame(frame);
    if (seen && !document.hidden) frame = requestAnimationFrame(run);
  };
  const observer = new IntersectionObserver(([entry]) => {
    seen = Boolean(entry?.isIntersecting);
    sync();
  });
  observer.observe(element);
  document.addEventListener("visibilitychange", sync);
  return () => {
    observer.disconnect();
    document.removeEventListener("visibilitychange", sync);
    cancelAnimationFrame(frame);
  };
}

const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
const sourceEl = useTemplateRef<HTMLDivElement>("sourceRef");
const layerEl = useTemplateRef<HTMLDivElement>("layerRef");

/** Clone the next item to (x, y) once the pointer has travelled `threshold` px. At most `max` clones live at once. */
function createTrail(
  root: HTMLElement,
  source: HTMLElement,
  layer: HTMLElement,
) {
  const { threshold, variant, max, duration } = props;
  let last: { x: number; y: number } | null = null;
  let count = 0;
  let inside = false;

  const spawn = (x: number, y: number) => {
    const items = source.children;
    if (!items.length) return;
    if (last && Math.hypot(x - last.x, y - last.y) < threshold) return;
    last = { x, y };
    if (layer.children.length >= max) layer.firstElementChild?.remove();
    const item = items[count % items.length]!.cloneNode(true) as HTMLElement;
    item.style.left = `${x}px`;
    item.style.top = `${y}px`;
    layer.append(item);
    const stack = variant === "stack";
    const animation = item.animate?.(frames(variant, count), {
      duration: stack ? duration * 0.4 : duration,
      easing: "cubic-bezier(.2,.7,.3,1)",
      fill: "forwards",
    });
    if (animation && !stack) animation.onfinish = () => item.remove();
    count++;
  };

  const move = (event: PointerEvent) => {
    if (still()) return;
    inside = true;
    const rect = root.getBoundingClientRect();
    spawn(event.clientX - rect.left, event.clientY - rect.top);
  };
  const leave = () => {
    inside = false;
    last = null;
    if (variant !== "stack") return;
    for (const item of [...layer.children]) {
      const out = item.animate?.([{ opacity: 1 }, { opacity: 0 }], {
        duration: 300,
        fill: "forwards",
      });
      if (out) out.onfinish = () => item.remove();
      else item.remove();
    }
  };

  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);
  const stopAuto =
    props.autoplay && !still() && typeof IntersectionObserver === "function"
      ? whileVisible(root, (now) => {
          if (inside) return;
          const t = now / 1100;
          const { width, height } = root.getBoundingClientRect();
          spawn(
            width * (0.5 + 0.36 * Math.sin(t)),
            height * (0.5 + 0.3 * Math.sin(2 * t)),
          );
        })
      : null;

  return () => {
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    stopAuto?.();
    layer.replaceChildren();
  };
}

let stop = () => {};
const start = () => {
  stop();
  stop = createTrail(rootEl.value!, sourceEl.value!, layerEl.value!);
};
onMounted(start);
watch(
  () => [
    props.threshold,
    props.variant,
    props.max,
    props.duration,
    props.autoplay,
  ],
  start,
);
onBeforeUnmount(() => stop());
</script>

<template>
  <div ref="rootRef" :class="base">
    <div ref="sourceRef" hidden>
      <slot name="items"><span :class="dotClass"></span></slot>
    </div>
    <div ref="layerRef" aria-hidden="true" :class="layerClass"></div>
    <slot />
  </div>
</template>
```

```vue
<template>
  <ImageTrail
    variant="scale"
    :threshold="48"
    class="grid h-72 place-items-center rounded-xl bg-subtle"
  >
    <template #items>
      <img src="/img/shoe-1.webp" alt="" class="w-20 rounded-lg" />
      <img src="/img/shoe-2.webp" alt="" class="w-20 rounded-lg" />
      <img src="/img/shoe-3.webp" alt="" class="w-20 rounded-lg" />
    </template>
    <h2 class="text-2xl font-semibold">New season sneakers</h2>
  </ImageTrail>
</template>
```

### Svelte

Save at `src/lib/components/markas/ImageTrail.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLAttributes } from "svelte/elements";

  type ImageTrailVariant = "fade" | "scale" | "rotate" | "stack";

  const base = "relative isolate overflow-hidden";
  const layerClass =
    "pointer-events-none absolute inset-0 -z-10 [&>*]:absolute [&>*]:-translate-x-1/2 [&>*]:-translate-y-1/2 [&>*]:opacity-0 motion-reduce:hidden";
  const dotClass = "block size-4 rounded-full bg-primary";

  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

  type Frame = { opacity: number; transform?: string; offset?: number };

  /** Keyframes per variant. The angle comes from the trail counter, so every run looks the same. */
  function frames(variant: ImageTrailVariant, n: number): Frame[] {
    const turn = ((n * 47) % 70) - 35;
    if (variant === "scale")
      return [
        { opacity: 1, transform: "scale(0)" },
        { opacity: 1, transform: "scale(1)", offset: 0.25 },
        { opacity: 0, transform: "scale(0.2)" },
      ];
    if (variant === "rotate")
      return [
        { opacity: 0, transform: `rotate(${turn}deg) scale(.6)` },
        {
          opacity: 1,
          transform: `rotate(${turn / 2}deg) scale(1)`,
          offset: 0.2,
        },
        { opacity: 0, transform: "rotate(0deg) translateY(32px) scale(.9)" },
      ];
    if (variant === "stack")
      return [
        { opacity: 0, transform: `rotate(${turn / 3}deg) scale(1.4)` },
        { opacity: 1, transform: `rotate(${turn / 3}deg) scale(1)` },
      ];
    return [{ opacity: 1 }, { opacity: 0 }];
  }

  type TrailOptions = {
    threshold: number;
    variant: ImageTrailVariant;
    max: number;
    duration: number;
    autoplay: boolean;
  };

  /** Run `tick` on every frame while the element is on screen and the tab is visible. */
  function whileVisible(element: Element, tick: (now: number) => void) {
    let frame = 0;
    let seen = false;
    const run = (now: number) => {
      tick(now);
      frame = requestAnimationFrame(run);
    };
    const sync = () => {
      cancelAnimationFrame(frame);
      if (seen && !document.hidden) frame = requestAnimationFrame(run);
    };
    const observer = new IntersectionObserver(([entry]) => {
      seen = Boolean(entry?.isIntersecting);
      sync();
    });
    observer.observe(element);
    document.addEventListener("visibilitychange", sync);
    return () => {
      observer.disconnect();
      document.removeEventListener("visibilitychange", sync);
      cancelAnimationFrame(frame);
    };
  }

  /** Clone the next item to (x, y) once the pointer has travelled `threshold` px. At most `max` clones live at once. */
  function createTrail(
    root: HTMLElement,
    source: HTMLElement,
    layer: HTMLElement,
    options: TrailOptions,
  ) {
    const { threshold, variant, max, duration } = options;
    let last: { x: number; y: number } | null = null;
    let count = 0;
    let inside = false;

    const spawn = (x: number, y: number) => {
      const items = source.children;
      if (!items.length) return;
      if (last && Math.hypot(x - last.x, y - last.y) < threshold) return;
      last = { x, y };
      if (layer.children.length >= max) layer.firstElementChild?.remove();
      const item = items[count % items.length]!.cloneNode(true) as HTMLElement;
      item.style.left = `${x}px`;
      item.style.top = `${y}px`;
      layer.append(item);
      const stack = variant === "stack";
      const animation = item.animate?.(frames(variant, count), {
        duration: stack ? duration * 0.4 : duration,
        easing: "cubic-bezier(.2,.7,.3,1)",
        fill: "forwards",
      });
      if (animation && !stack) animation.onfinish = () => item.remove();
      count++;
    };

    const move = (event: PointerEvent) => {
      if (still()) return;
      inside = true;
      const rect = root.getBoundingClientRect();
      spawn(event.clientX - rect.left, event.clientY - rect.top);
    };
    const leave = () => {
      inside = false;
      last = null;
      if (variant !== "stack") return;
      for (const item of [...layer.children]) {
        const out = item.animate?.([{ opacity: 1 }, { opacity: 0 }], {
          duration: 300,
          fill: "forwards",
        });
        if (out) out.onfinish = () => item.remove();
        else item.remove();
      }
    };

    root.addEventListener("pointermove", move);
    root.addEventListener("pointerleave", leave);
    const stopAuto =
      options.autoplay && !still() && typeof IntersectionObserver === "function"
        ? whileVisible(root, (now) => {
            if (inside) return;
            const t = now / 1100;
            const { width, height } = root.getBoundingClientRect();
            spawn(
              width * (0.5 + 0.36 * Math.sin(t)),
              height * (0.5 + 0.3 * Math.sin(2 * t)),
            );
          })
        : null;

    return () => {
      root.removeEventListener("pointermove", move);
      root.removeEventListener("pointerleave", leave);
      stopAuto?.();
      layer.replaceChildren();
    };
  }

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** Elements that appear along the trail, cloned in order. A small primary dot when empty. */
    items?: Snippet;
    /** Distance in px the pointer travels before the next item appears. */
    threshold?: number;
    /** How each item enters and leaves. */
    variant?: ImageTrailVariant;
    /** Most items on screen at once. */
    max?: number;
    /** Life of one item in ms. */
    duration?: number;
    /** Draws a figure-eight trail on its own while visible and the pointer is elsewhere. */
    autoplay?: boolean;
    children?: Snippet;
  };

  let {
    items,
    threshold = 40,
    variant = "fade",
    max = 12,
    duration = 800,
    autoplay = false,
    class: className,
    children,
    ...rest
  }: Props = $props();

  let root = $state<HTMLDivElement>();
  let source = $state<HTMLDivElement>();
  let layer = $state<HTMLDivElement>();

  $effect(() => {
    const options = { threshold, variant, max, duration, autoplay };
    if (root && source && layer)
      return createTrail(root, source, layer, options);
  });
</script>

<div {...rest} bind:this={root} class={[base, className]}>
  <div bind:this={source} hidden>
    {#if items}{@render items()}{:else}<span class={dotClass}></span>{/if}
  </div>
  <div bind:this={layer} aria-hidden="true" class={layerClass}></div>
  {@render children?.()}
</div>
```

```svelte
<script lang="ts">
  import ImageTrail from "$lib/components/markas/ImageTrail.svelte";
</script>

<ImageTrail
  variant="scale"
  threshold={48}
  class="grid h-72 place-items-center rounded-xl bg-subtle"
>
  {#snippet items()}
    <img src="/img/shoe-1.webp" alt="" class="w-20 rounded-lg" />
    <img src="/img/shoe-2.webp" alt="" class="w-20 rounded-lg" />
  {/snippet}
  <h2 class="text-2xl font-semibold">New season sneakers</h2>
</ImageTrail>
```

### Astro

Save at `src/components/markas/ImageTrail.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

type ImageTrailVariant = "fade" | "scale" | "rotate" | "stack";

const base = "relative isolate overflow-hidden";
const layerClass =
  "pointer-events-none absolute inset-0 -z-10 [&>*]:absolute [&>*]:-translate-x-1/2 [&>*]:-translate-y-1/2 [&>*]:opacity-0 motion-reduce:hidden";
const dotClass = "block size-4 rounded-full bg-primary";

type Props = HTMLAttributes<"div"> & {
  /** Distance in px the pointer travels before the next item appears. */
  threshold?: number;
  /** How each item enters and leaves. */
  variant?: ImageTrailVariant;
  /** Most items on screen at once. */
  max?: number;
  /** Life of one item in ms. */
  duration?: number;
  /** Draws a figure-eight trail on its own while visible and the pointer is elsewhere. */
  autoplay?: boolean;
};

const {
  threshold = 40,
  variant = "fade",
  max = 12,
  duration = 800,
  autoplay = false,
  class: className,
  ...rest
} = Astro.props;
const options = JSON.stringify({
  threshold: Number(threshold),
  variant,
  max: Number(max),
  duration: Number(duration),
  autoplay: Boolean(autoplay),
});
---

<markas-image-trail class="contents" data-options={options}>
  <div {...rest} class:list={[base, className]}>
    <div hidden><slot name="items"><span class={dotClass}></span></slot></div>
    <div aria-hidden="true" class={layerClass}></div>
    <slot />
  </div>
</markas-image-trail>

<script>
  type ImageTrailVariant = "fade" | "scale" | "rotate" | "stack";

  const still = () =>
    window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

  type Frame = { opacity: number; transform?: string; offset?: number };

  /** Keyframes per variant. The angle comes from the trail counter, so every run looks the same. */
  function frames(variant: ImageTrailVariant, n: number): Frame[] {
    const turn = ((n * 47) % 70) - 35;
    if (variant === "scale")
      return [
        { opacity: 1, transform: "scale(0)" },
        { opacity: 1, transform: "scale(1)", offset: 0.25 },
        { opacity: 0, transform: "scale(0.2)" },
      ];
    if (variant === "rotate")
      return [
        { opacity: 0, transform: `rotate(${turn}deg) scale(.6)` },
        { opacity: 1, transform: `rotate(${turn / 2}deg) scale(1)`, offset: 0.2 },
        { opacity: 0, transform: "rotate(0deg) translateY(32px) scale(.9)" },
      ];
    if (variant === "stack")
      return [
        { opacity: 0, transform: `rotate(${turn / 3}deg) scale(1.4)` },
        { opacity: 1, transform: `rotate(${turn / 3}deg) scale(1)` },
      ];
    return [{ opacity: 1 }, { opacity: 0 }];
  }

  type TrailOptions = {
    threshold: number;
    variant: ImageTrailVariant;
    max: number;
    duration: number;
    autoplay: boolean;
  };

  /** Run `tick` on every frame while the element is on screen and the tab is visible. */
  function whileVisible(element: Element, tick: (now: number) => void) {
    let frame = 0;
    let seen = false;
    const run = (now: number) => {
      tick(now);
      frame = requestAnimationFrame(run);
    };
    const sync = () => {
      cancelAnimationFrame(frame);
      if (seen && !document.hidden) frame = requestAnimationFrame(run);
    };
    const observer = new IntersectionObserver(([entry]) => {
      seen = Boolean(entry?.isIntersecting);
      sync();
    });
    observer.observe(element);
    document.addEventListener("visibilitychange", sync);
    return () => {
      observer.disconnect();
      document.removeEventListener("visibilitychange", sync);
      cancelAnimationFrame(frame);
    };
  }

  /** Clone the next item to (x, y) once the pointer has travelled `threshold` px. At most `max` clones live at once. */
  function createTrail(
    root: HTMLElement,
    source: HTMLElement,
    layer: HTMLElement,
    options: TrailOptions,
  ) {
    const { threshold, variant, max, duration } = options;
    let last: { x: number; y: number } | null = null;
    let count = 0;
    let inside = false;

    const spawn = (x: number, y: number) => {
      const items = source.children;
      if (!items.length) return;
      if (last && Math.hypot(x - last.x, y - last.y) < threshold) return;
      last = { x, y };
      if (layer.children.length >= max) layer.firstElementChild?.remove();
      const item = items[count % items.length]!.cloneNode(true) as HTMLElement;
      item.style.left = `${x}px`;
      item.style.top = `${y}px`;
      layer.append(item);
      const stack = variant === "stack";
      const animation = item.animate?.(frames(variant, count), {
        duration: stack ? duration * 0.4 : duration,
        easing: "cubic-bezier(.2,.7,.3,1)",
        fill: "forwards",
      });
      if (animation && !stack) animation.onfinish = () => item.remove();
      count++;
    };

    const move = (event: PointerEvent) => {
      if (still()) return;
      inside = true;
      const rect = root.getBoundingClientRect();
      spawn(event.clientX - rect.left, event.clientY - rect.top);
    };
    const leave = () => {
      inside = false;
      last = null;
      if (variant !== "stack") return;
      for (const item of [...layer.children]) {
        const out = item.animate?.([{ opacity: 1 }, { opacity: 0 }], {
          duration: 300,
          fill: "forwards",
        });
        if (out) out.onfinish = () => item.remove();
        else item.remove();
      }
    };

    root.addEventListener("pointermove", move);
    root.addEventListener("pointerleave", leave);
    const stopAuto =
      options.autoplay && !still() && typeof IntersectionObserver === "function"
        ? whileVisible(root, (now) => {
            if (inside) return;
            const t = now / 1100;
            const { width, height } = root.getBoundingClientRect();
            spawn(
              width * (0.5 + 0.36 * Math.sin(t)),
              height * (0.5 + 0.3 * Math.sin(2 * t)),
            );
          })
        : null;

    return () => {
      root.removeEventListener("pointermove", move);
      root.removeEventListener("pointerleave", leave);
      stopAuto?.();
      layer.replaceChildren();
    };
  }


  // Per instance: each area follows its own pointer and runs its own autoplay loop.
  class ImageTrail extends HTMLElement {
    #stop = () => {};

    connectedCallback() {
      const root = this.firstElementChild as HTMLElement | null;
      const [source, layer] = (root?.children ?? []) as HTMLCollectionOf<HTMLElement>;
      if (!root || !source || !layer) return;
      this.#stop = createTrail(
        root,
        source,
        layer,
        JSON.parse(this.dataset.options ?? "{}") as TrailOptions,
      );
    }

    disconnectedCallback() {
      this.#stop();
    }
  }

  if (!customElements.get("markas-image-trail"))
    customElements.define("markas-image-trail", ImageTrail);
</script>
```

```astro
---
import ImageTrail from "@/components/markas/ImageTrail.astro";
---

<ImageTrail
  variant="scale"
  threshold={48}
  class="grid h-72 place-items-center rounded-xl bg-subtle"
>
  <Fragment slot="items">
    <img src="/img/shoe-1.webp" alt="" class="w-20 rounded-lg" />
    <img src="/img/shoe-2.webp" alt="" class="w-20 rounded-lg" />
  </Fragment>
  <h2 class="text-2xl font-semibold">New season sneakers</h2>
</ImageTrail>
```

A small bundled script runs each trail through the `markas-image-trail` element.

### Angular

Save at `src/app/markas/image-trail.component.ts`. No extra dependencies.

```ts
import {
  afterRenderEffect,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  numberAttribute,
  viewChild,
} from "@angular/core";

export type ImageTrailVariant = "fade" | "scale" | "rotate" | "stack";

const base = "relative isolate overflow-hidden";
const layerClass =
  "pointer-events-none absolute inset-0 -z-10 [&>*]:absolute [&>*]:-translate-x-1/2 [&>*]:-translate-y-1/2 [&>*]:opacity-0 motion-reduce:hidden";
const dotClass = "block size-4 rounded-full bg-primary";

const still = () =>
  window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;

type Frame = { opacity: number; transform?: string; offset?: number };

/** Keyframes per variant. The angle comes from the trail counter, so every run looks the same. */
function frames(variant: ImageTrailVariant, n: number): Frame[] {
  const turn = ((n * 47) % 70) - 35;
  if (variant === "scale")
    return [
      { opacity: 1, transform: "scale(0)" },
      { opacity: 1, transform: "scale(1)", offset: 0.25 },
      { opacity: 0, transform: "scale(0.2)" },
    ];
  if (variant === "rotate")
    return [
      { opacity: 0, transform: `rotate(${turn}deg) scale(.6)` },
      { opacity: 1, transform: `rotate(${turn / 2}deg) scale(1)`, offset: 0.2 },
      { opacity: 0, transform: "rotate(0deg) translateY(32px) scale(.9)" },
    ];
  if (variant === "stack")
    return [
      { opacity: 0, transform: `rotate(${turn / 3}deg) scale(1.4)` },
      { opacity: 1, transform: `rotate(${turn / 3}deg) scale(1)` },
    ];
  return [{ opacity: 1 }, { opacity: 0 }];
}

type TrailOptions = {
  threshold: number;
  variant: ImageTrailVariant;
  max: number;
  duration: number;
  autoplay: boolean;
};

/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
  let frame = 0;
  let seen = false;
  const run = (now: number) => {
    tick(now);
    frame = requestAnimationFrame(run);
  };
  const sync = () => {
    cancelAnimationFrame(frame);
    if (seen && !document.hidden) frame = requestAnimationFrame(run);
  };
  const observer = new IntersectionObserver(([entry]) => {
    seen = Boolean(entry?.isIntersecting);
    sync();
  });
  observer.observe(element);
  document.addEventListener("visibilitychange", sync);
  return () => {
    observer.disconnect();
    document.removeEventListener("visibilitychange", sync);
    cancelAnimationFrame(frame);
  };
}

/** Clone the next item to (x, y) once the pointer has travelled `threshold` px. At most `max` clones live at once. */
function createTrail(
  root: HTMLElement,
  source: HTMLElement,
  layer: HTMLElement,
  options: TrailOptions,
) {
  const { threshold, variant, max, duration } = options;
  let last: { x: number; y: number } | null = null;
  let count = 0;
  let inside = false;

  const spawn = (x: number, y: number) => {
    const items = source.children;
    if (!items.length) return;
    if (last && Math.hypot(x - last.x, y - last.y) < threshold) return;
    last = { x, y };
    if (layer.children.length >= max) layer.firstElementChild?.remove();
    const item = items[count % items.length]!.cloneNode(true) as HTMLElement;
    item.style.left = `${x}px`;
    item.style.top = `${y}px`;
    layer.append(item);
    const stack = variant === "stack";
    const animation = item.animate?.(frames(variant, count), {
      duration: stack ? duration * 0.4 : duration,
      easing: "cubic-bezier(.2,.7,.3,1)",
      fill: "forwards",
    });
    if (animation && !stack) animation.onfinish = () => item.remove();
    count++;
  };

  const move = (event: PointerEvent) => {
    if (still()) return;
    inside = true;
    const rect = root.getBoundingClientRect();
    spawn(event.clientX - rect.left, event.clientY - rect.top);
  };
  const leave = () => {
    inside = false;
    last = null;
    if (variant !== "stack") return;
    for (const item of [...layer.children]) {
      const out = item.animate?.([{ opacity: 1 }, { opacity: 0 }], {
        duration: 300,
        fill: "forwards",
      });
      if (out) out.onfinish = () => item.remove();
      else item.remove();
    }
  };

  root.addEventListener("pointermove", move);
  root.addEventListener("pointerleave", leave);
  const stopAuto =
    options.autoplay && !still() && typeof IntersectionObserver === "function"
      ? whileVisible(root, (now) => {
          if (inside) return;
          const t = now / 1100;
          const { width, height } = root.getBoundingClientRect();
          spawn(
            width * (0.5 + 0.36 * Math.sin(t)),
            height * (0.5 + 0.3 * Math.sin(2 * t)),
          );
        })
      : null;

  return () => {
    root.removeEventListener("pointermove", move);
    root.removeEventListener("pointerleave", leave);
    stopAuto?.();
    layer.replaceChildren();
  };
}

/**
 * Slots: an element with the `items` attribute (an ng-container works) holds the elements cloned
 * along the trail; everything else is the content. The host stays out of layout; the user's class
 * lands on the area.
 */
@Component({
  selector: "markas-image-trail",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents" },
  template: `
    <div #rootEl [class]="classes()">
      <div #sourceEl hidden>
        <ng-content select="[items]"
          ><span [class]="dotClass"></span
        ></ng-content>
      </div>
      <div #layerEl aria-hidden="true" [class]="layerClass"></div>
      <ng-content />
    </div>
  `,
})
export class ImageTrail {
  /** Distance in px the pointer travels before the next item appears. */
  readonly threshold = input(40, { transform: numberAttribute });
  /** How each item enters and leaves. */
  readonly variant = input<ImageTrailVariant>("fade");
  /** Most items on screen at once. */
  readonly max = input(12, { transform: numberAttribute });
  /** Life of one item in ms. */
  readonly duration = input(800, { transform: numberAttribute });
  /** Draws a figure-eight trail on its own while visible and the pointer is elsewhere. */
  readonly autoplay = input(false, { transform: booleanAttribute });
  readonly userClass = input("", { alias: "class" });

  protected readonly dotClass = dotClass;
  protected readonly layerClass = layerClass;
  protected readonly classes = computed(() =>
    [base, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly root = viewChild.required<ElementRef<HTMLElement>>("rootEl");
  private readonly source =
    viewChild.required<ElementRef<HTMLElement>>("sourceEl");
  private readonly layer =
    viewChild.required<ElementRef<HTMLElement>>("layerEl");

  constructor() {
    afterRenderEffect((onCleanup) => {
      const options = {
        threshold: this.threshold(),
        variant: this.variant(),
        max: this.max(),
        duration: this.duration(),
        autoplay: this.autoplay(),
      };
      onCleanup(
        createTrail(
          this.root().nativeElement,
          this.source().nativeElement,
          this.layer().nativeElement,
          options,
        ),
      );
    });
  }
}
```

```ts
import { Component } from "@angular/core";
import { ImageTrail } from "./markas/image-trail.component";

@Component({
  selector: "app-sneakers",
  imports: [ImageTrail],
  template: `
    <markas-image-trail
      variant="scale"
      [threshold]="48"
      class="grid h-72 place-items-center rounded-xl bg-subtle"
    >
      <ng-container items>
        <img src="/img/shoe-1.webp" alt="" class="w-20 rounded-lg" />
        <img src="/img/shoe-2.webp" alt="" class="w-20 rounded-lg" />
      </ng-container>
      <h2 class="text-2xl font-semibold">New season sneakers</h2>
    </markas-image-trail>
  `,
})
export class Sneakers {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `ReactNode / slot #items` | primary dot | Elements that appear along the trail, cloned one after another. Images, token color cards, emoji, or initials. |
| `variant` | `"fade" \| "scale" \| "rotate" \| "stack"` | "fade" | fade: appear and fade out. scale: pop in and shrink away. rotate: spin in and drop while fading. stack: pile up like photos until the pointer leaves. |
| `threshold` | `number` | 40 | Distance in px the pointer travels before the next item appears. Larger values give a sparser trail. |
| `max` | `number` | 12 | Most items on screen at once. The oldest is removed first, so the DOM stays small. |
| `duration` | `number` | 800 | Life of one item in ms. In stack, items enter in 40% of this and stay until the pointer leaves. |
| `autoplay` | `boolean` | false | Draws a figure-eight trail on its own while the area is on screen, the tab is visible, and the pointer is elsewhere. Handy on touch screens. |
| `children / slot` | `ReactNode / slot` | - | Content shown above the trail. Lay it out with your own classes on the component (grid, height, padding). |

## Accessibility

- Trail items are clones inside an aria-hidden layer that never catches the pointer; the source items sit in a hidden element, so screen readers only read the content.
- The trail sits behind the content, so text and buttons stay readable and clickable.
- With reduced motion no trail is drawn and autoplay stays off.

## Notes

- Items are cloned in order to the pointer every `threshold` px. At most `max` clones live at once and finished ones are removed, so the DOM stays small.
- `variant`: `fade`, `scale`, `rotate` (the angle follows a fixed pattern, so every run looks the same), or `stack`, where items pile up until the pointer leaves.
- `autoplay` draws a figure-eight trail while the area is on screen and the pointer is elsewhere. It pauses when the area scrolls away or the tab is hidden.
- The trail sits behind the content and is aria-hidden. With reduced motion nothing is drawn. Attributes and `class` go to the area itself.
