---
title: Mouse trail
description: An image trail that follows the cursor.
category: Cursor
tier: free
url: https://ui.dimaac.com/components/mouse-trail
registry: https://ui.dimaac.com/r/mouse-trail.json
---

# Mouse trail

A stack of photo cards that follows the pointer. Each card runs a moment behind the one above it, so the stack stretches into a trail when you move and gathers again when you stop. It listens only inside its own box (two on a page never touch each other), works with touch, drifts along a slow loop by itself on touch screens, and sits still, fanned out, when the visitor prefers reduced motion. Ported from the first DiMaac UI and rebuilt with scoped GSAP quickTo calls.

## Install

With the shadcn CLI:

```bash
npx shadcn@latest add https://ui.dimaac.com/r/mouse-trail.json
pnpm dlx shadcn@latest add https://ui.dimaac.com/r/mouse-trail.json
bunx --bun shadcn@latest add https://ui.dimaac.com/r/mouse-trail.json
```

With the `@dimaac` namespace in components.json: `npx shadcn@latest add @dimaac/mouse-trail`

Dependencies:

```bash
pnpm add gsap @gsap/react
npm install gsap @gsap/react
```

By hand:

1. Install the packages it uses: gsap, @gsap/react.
2. Copy the component file below into components/dimaac/mouse-trail.tsx.
3. It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
4. Import it with import { MouseTrail } from "@/components/dimaac/mouse-trail". Give its parent a size: it fills it.

## Usage

```tsx
import { MouseTrail } from "@/components/dimaac/mouse-trail";

<MouseTrail images={images} />
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `images` (required) | `string[]` | - | The photos, top card first. Six to twelve look best. |
| `imageWidth` | `number` | `170` | Width of each card, in pixels. |
| `imageHeight` | `number` | `238` | Height of each card, in pixels. |
| `stagger` | `number` | `0.04` | How far behind the card above it each card runs, in seconds. |
| `duration` | `number` | `0.5` | How long a card takes to catch up with its spot, in seconds. |
| `ease` | `string` | `"power3.out"` | The GSAP ease of that catch-up, e.g. "power2.out" or "expo.out". |
| `autoplay` | `"touch" \| "always" \| "never"` | `"touch"` | When the stack drifts by itself: on touch screens only, always (whenever no pointer is over it) or never. |
| `className` | `string` | `""` | Extra classes for the outer box. Give it a size (it fills it). |
| `imageClassName` | `string` | `"rounded-[4px] shadow-[0_16px_34px_-14px_rgba(0,0,0,0.3)]"` | Extra classes for each card, e.g. a radius or a shadow. |

## Credits

- Photos: Lummi, Lummi (https://www.lummi.ai), Lummi License (free for personal and commercial use)

## Source

### mouse-trail.tsx → `components/dimaac/mouse-trail.tsx`

```tsx
"use client";

import { useRef } from "react";
import { gsap } from "gsap";
import { useGSAP } from "@gsap/react";

// A stack of photos that chases the cursor. Every card follows the same path a little later than
// the one above it, so the stack stretches into a trail when you move and gathers when you stop.
// On touch screens (or always, if you ask) it drifts along a slow loop by itself.

export type MouseTrailProps = {
  /** The photos, top card first. Six to twelve look best. */
  images: string[];
  /** Width of each card, in pixels. */
  imageWidth?: number;
  /** Height of each card, in pixels. */
  imageHeight?: number;
  /** How far behind the card above it each card runs, in seconds. */
  stagger?: number;
  /** How long a card takes to catch up with its spot, in seconds. */
  duration?: number;
  /** The GSAP ease of that catch-up, e.g. "power2.out" or "expo.out". */
  ease?: string;
  /** When the stack drifts by itself: on touch screens only, always (whenever no pointer is over it) or never. */
  autoplay?: "touch" | "always" | "never";
  /** Extra classes for the outer box. Give it a size (it fills it). */
  className?: string;
  /** Extra classes for each card, e.g. a radius or a shadow. */
  imageClassName?: string;
};

type Point = { t: number; x: number; y: number };

export function MouseTrail({
  images,
  imageWidth = 170,
  imageHeight = 238,
  stagger = 0.04,
  duration = 0.5,
  ease = "power3.out",
  autoplay = "touch",
  className = "",
  imageClassName = "rounded-[4px] shadow-[0_16px_34px_-14px_rgba(0,0,0,0.3)]",
}: MouseTrailProps) {
  const boxRef = useRef<HTMLDivElement>(null);
  const cardRefs = useRef<(HTMLDivElement | null)[]>([]);
  // Read on every frame, so a new stagger doesn't rebuild anything
  const staggerRef = useRef(stagger);
  staggerRef.current = stagger;

  useGSAP(
    (_context, contextSafe) => {
      const box = boxRef.current;
      const cards = cardRefs.current.slice(0, images.length).filter((card): card is HTMLDivElement => card !== null);
      if (!box || cards.length === 0 || !contextSafe) return;

      gsap.set(cards, { xPercent: -50, yPercent: -50, x: box.clientWidth / 2, y: box.clientHeight / 2, force3D: true });

      // Reduced motion: no chase. The stack sits in the middle, fanned out a little, and stays put.
      const mm = gsap.matchMedia();
      mm.add("(prefers-reduced-motion: reduce)", () => {
        const middle = (cards.length - 1) / 2;
        gsap.set(cards.map((card) => card.firstElementChild), { opacity: 1 });
        gsap.set(cards, { opacity: 1, left: "50%", top: "50%", x: 0, y: 0, rotation: (i: number) => (i - middle) * 4, xPercent: (i: number) => -50 + (i - middle) * 6 });
      });

      const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      if (reduced) return () => mm.revert();

      const touchScreen = window.matchMedia("(hover: none)").matches;
      const drifts = autoplay === "always" || (autoplay === "touch" && touchScreen);

      // One quickTo per card and axis: cheap to call every frame, eased toward the newest value
      const moveX = cards.map((card) => gsap.quickTo(card, "x", { duration, ease }));
      const moveY = cards.map((card) => gsap.quickTo(card, "y", { duration, ease }));
      // A card that sits right under the one above it is hidden, so ten shadows don't pile up
      // into a dark halo when the stack gathers. It fades in as it pulls away.
      const fade = cards.map((card) => gsap.quickSetter(card.firstElementChild, "opacity"));

      // Where the trail's head has been, so each card can be sent where the head was a moment ago
      const history: Point[] = [];
      const target = { x: box.clientWidth / 2, y: box.clientHeight / 2 };
      let pointerInside = false;
      let lastInput = -Infinity;
      let shown = false;
      let visible = true;
      let clock = 0;

      const show = (on: boolean) => {
        if (on === shown) return;
        shown = on;
        gsap.to(cards, { opacity: on ? 1 : 0, duration: on ? 0.25 : 0.4, ease: "power2.out", stagger: on ? staggerRef.current / 2 : 0, overwrite: "auto" });
      };

      const pointAt = (time: number): Point => {
        for (let i = history.length - 1; i >= 0; i--) if (history[i]!.t <= time) return history[i]!;
        return history[0] ?? { t: time, x: target.x, y: target.y };
      };

      const tick = (seconds: number) => {
        if (!visible) return;
        clock = seconds;
        const idle = seconds - lastInput > 1.2 && !pointerInside;
        if (drifts && idle) {
          // A slow figure of eight around the middle of the box
          const w = box.clientWidth;
          const h = box.clientHeight;
          target.x = w / 2 + Math.sin(seconds * 0.8) * w * 0.28;
          target.y = h / 2 + Math.sin(seconds * 1.6) * h * 0.2;
          show(true);
        }
        history.push({ t: seconds, x: target.x, y: target.y });
        const keep = cards.length * staggerRef.current + 0.5;
        while (history.length > 2 && history[0]!.t < seconds - keep) history.shift();
        cards.forEach((_, i) => {
          const point = pointAt(seconds - i * staggerRef.current);
          moveX[i]!(point.x);
          moveY[i]!(point.y);
          if (i === 0) return;
          const above = cards[i - 1]!;
          const gap = Math.hypot(Number(gsap.getProperty(cards[i]!, "x")) - Number(gsap.getProperty(above, "x")), Number(gsap.getProperty(cards[i]!, "y")) - Number(gsap.getProperty(above, "y")));
          fade[i]!(Math.min(1, gap / 20));
        });
      };
      gsap.ticker.add(tick);

      const place = (event: PointerEvent) => {
        const rect = box.getBoundingClientRect();
        target.x = event.clientX - rect.left;
        target.y = event.clientY - rect.top;
        lastInput = clock;
      };

      const onPointerMove = contextSafe((event: PointerEvent) => {
        if (!event.isPrimary) return;
        place(event);
        show(true);
      });
      const onPointerEnter = contextSafe((event: PointerEvent) => {
        if (event.pointerType === "mouse" || event.pointerType === "pen") pointerInside = true;
      });
      const onPointerDown = contextSafe((event: PointerEvent) => {
        if (!event.isPrimary) return;
        place(event);
        show(true);
      });
      const onPointerLeave = contextSafe(() => {
        pointerInside = false;
        if (!drifts) show(false);
      });

      box.addEventListener("pointermove", onPointerMove);
      box.addEventListener("pointerenter", onPointerEnter);
      box.addEventListener("pointerdown", onPointerDown);
      box.addEventListener("pointerleave", onPointerLeave);

      // No work while the box is off screen
      const visibility = new IntersectionObserver(([entry]) => {
        visible = entry?.isIntersecting ?? true;
      });
      visibility.observe(box);

      return () => {
        gsap.ticker.remove(tick);
        visibility.disconnect();
        box.removeEventListener("pointermove", onPointerMove);
        box.removeEventListener("pointerenter", onPointerEnter);
        box.removeEventListener("pointerdown", onPointerDown);
        box.removeEventListener("pointerleave", onPointerLeave);
        mm.revert();
      };
    },
    { scope: boxRef, dependencies: [images.length, duration, ease, autoplay], revertOnUpdate: true },
  );

  return (
    <div ref={boxRef} className={`relative h-full w-full overflow-hidden ${className}`} style={{ touchAction: "pan-y" }}>
      {images.map((src, index) => (
        <div
          key={`${index}-${src}`}
          ref={(card) => {
            cardRefs.current[index] = card;
          }}
          className="pointer-events-none absolute top-0 left-0 opacity-0"
          style={{ width: imageWidth, height: imageHeight, zIndex: images.length - index, willChange: "transform, opacity" }}
        >
          <div className={`h-full w-full overflow-hidden ${imageClassName}`}>
            <img src={src} alt="" className="block h-full w-full object-cover" draggable={false} decoding="async" />
          </div>
        </div>
      ))}
    </div>
  );
}
```

### demo.tsx (the demo on the page, not installed)

```tsx
"use client";

import { MouseTrail, type MouseTrailProps } from "@/components/dimaac/mouse-trail";

// Ten Lummi photos (Lummi License: free for personal and commercial use)
const photos = [
  "QmedKm8YSdHaWnDdvLzjrsWgeiArndQkhcucsvaFjyVgXz",
  "QmcR7gTkJUJgUAfWjM31hbEMJ43txn6aTiJx7hb8LaVQ5X",
  "QmTSgovioSANEhNgNo9XxY3ug5iYfQ1wnjY2P72qZofRwP",
  "Qmb3rGQC9S1bGz7PC5cnQ3y2cX3GnDpUeBYx9vQvSn1H3v",
  "QmXzqMzfHMyvQBySMwJdgUbUYsTNUNbDD2bLCyDt5s7aQU",
  "QmbWtf1Mhr3JCLd7NS4XQ187cA7ukws3zuDXTcbd8fGo5u",
  "QmSoKRoG5ZTST6n9eWmLqggURiirGS3W4LfZ338Wj2puki",
  "Qme6mAjMnD8PLhRzHZ7soZG2cvZL5vHPhzoA5pm6JuaCSX",
  "QmUU9hRVuK34EFbA4DNMEMrQ6X4NnqTg2Dppqv6R3jCMQC",
  "QmStPNbdbM4Acy1UDESHguBMqWLCw53WWUvxXXdqKAcVvq",
].map((id) => `https://assets.lummi.ai/assets/${id}?auto=format&w=480`);

export default function Demo(props: Partial<MouseTrailProps>) {
  return (
    <div className="relative h-full w-full cursor-crosshair overflow-hidden bg-[#f3f0eb] text-[#1c1917] dark:bg-[#0f0b0b] dark:text-[#e8ddd4]">
      <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-4 px-6 text-center">
        <h1 className="text-[clamp(44px,9vw,128px)] leading-[0.92] font-medium tracking-[-0.045em] opacity-90">
          Small things,
          <br />
          seen slowly
        </h1>
        <p className="max-w-[34ch] text-[15px] opacity-60">Move across the page to leave a trail of photographs.</p>
      </div>

      <MouseTrail images={photos} {...props} className={`absolute inset-0 z-10 ${props.className ?? ""}`} />
    </div>
  );
}
```

## Agent prompt

```text
Add the Mouse trail component (<MouseTrail />) from DiMaac UI to this project.

Docs: https://ui.dimaac.com/components/mouse-trail
Source and dependencies (shadcn registry JSON): https://ui.dimaac.com/r/mouse-trail.json

Install it with:
npx shadcn@latest add https://ui.dimaac.com/r/mouse-trail.json

Then use it like this:
import { MouseTrail } from "@/components/dimaac/mouse-trail";
<MouseTrail images={images} />

If the shadcn CLI isn't set up here, fetch the registry JSON above, write files[0].content to components/dimaac/mouse-trail.tsx and install gsap, @gsap/react.
It uses Tailwind v4 classes, so make sure Tailwind scans that folder. Give its parent a size: it fills it. Keep light and dark mode working and keep its prefers-reduced-motion fallback.
Full index for agents: https://ui.dimaac.com/llms.txt
```
