Mouse trail
An image trail that follows the cursor.
Customize
<MouseTrail images={images} />Changes show live and stay in the address, so a link keeps them.
Code
"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>
);
}
The component. Installs to components/dimaac/mouse-trail.tsx.
Install
With the shadcn CLI
npx shadcn@latest add https://ui.dimaac.com/r/mouse-trail.jsonIt adds components/dimaac/mouse-trail.tsx and installs what it imports. With the @dimaac namespace in components.json (Docs) it's just npx shadcn@latest add @dimaac/mouse-trail.
By hand
npm install gsap @gsap/react- Install the packages it uses: gsap, @gsap/react.
- Copy the component file below into components/dimaac/mouse-trail.tsx.
- It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
- Import it with import { MouseTrail } from "@/components/dimaac/mouse-trail". Give its parent a size: it fills it.
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. |
Use with AI
Agent prompt
Paste it into Claude Code, Cursor or any coding agent, or open it straight in a chat. It carries your Customize settings.
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.txtFiles agents read
- llms.txt
- Every component and how to install it
- mouse-trail.md
- This page as Markdown: install, props and the full source
- mouse-trail.json
- The shadcn registry item
About
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.
- Installs to
components/dimaac/mouse-trail.tsx- Uses
- gsap, @gsap/react
- Tags
- gsap, cursor, images, trail
Photos by Lummi on Lummi (Lummi License (free for personal and commercial use)).