# 光标图片拖尾（Image trail）

- 俗称：鼠标移动留下图片轨迹；光标图片拖尾淡出；画廊鼠标拖影；移动指针依次出图
- 用在：图片、背景（品牌官网、个人网站）
- 触发：悬停
- 感觉：俏皮、戏剧化
- 版本：1，更新于 2026-11-17

## 原理

监听 pointermove 计算与上次触发点的欧氏距离，只有超过距离阈值 threshold 才轮流取出池中下一张图片定位到当前光标处，防止高刷屏幕下爆出过多节点；再用 Web Animations API 播放放大出现并渐隐的动画，同时限制最大同屏节点数并复用 DOM；手机端与减少动态下自动降级为静态有序排布。

适合：作品集首屏、创意工作室、摄影展示页，用轻巧的视觉拖尾增强探索氛围。

## 参数

| 参数名 | 含义 | 默认值 | 建议范围 |
|---|---|---|---|
| `threshold` | 触发距离 | 48px | 20–140px |
| `duration` | 淡出时长 | 650ms | 250–1400ms |
| `easing` | 缓动 | cubic-bezier(0.22, 1, 0.36, 1) | — |

## 质量要求

- 开启"减少动态"时：关闭随指针生成的拖尾动画，保持卡片静态有序展示在舞台内。
- 手机上：触屏设备不触发悬停拖尾，直接展示精简后的静态叠放卡片。
- 动画只在播放时改变元素；脚本出错或没有执行时，内容照样可见（不要先用 CSS 把内容藏起来再等脚本显示）。

## 提示词（可以直接交给 AI）

```text
请在我的项目里给图片加上「光标图片拖尾」（Image trail）效果：监听 pointermove 计算与上次触发点的欧氏距离，只有超过距离阈值 threshold 才轮流取出池中下一张图片定位到当前光标处，防止高刷屏幕下爆出过多节点；再用 Web Animations API 播放放大出现并渐隐的动画，同时限制最大同屏节点数并复用 DOM；手机端与减少动态下自动降级为静态有序排布。
参数：触发距离 48px，淡出时长 650ms，缓动 cubic-bezier(0.22, 1, 0.36, 1)。
要求：保留原有的内容和布局；系统开启"减少动态"时直接显示最终状态；脚本出错或没有执行时内容仍然可见。
参考：https://donglang.linter.top/effects/image-trail.md（原理、参数和参考代码）
```

## 参考代码

HTML 结构：

```html
<div class="imt-stage" id="trail" style="height: 240px;">
  <div class="imt-item" style="width:96px;height:68px;background:#e0301e;border-radius:8px;"></div>
  <div class="imt-item" style="width:96px;height:68px;background:#141519;border-radius:8px;"></div>
  <div class="imt-item" style="width:96px;height:68px;background:#3f63c4;border-radius:8px;"></div>
  <div class="imt-item" style="width:96px;height:68px;background:#23855a;border-radius:8px;"></div>
</div>

<script type="module">
  import { imageTrail } from './image-trail.js';
  imageTrail(document.getElementById('trail'), { threshold: 48, duration: 650 });
</script>
```

CSS：

```css
/* 光标图片拖尾（Image trail）样式，配合 image-trail.js。 */
.imt-stage {
  position: relative;
  overflow: hidden;
  min-height: 160px;
}

.imt-item {
  position: absolute;
  left: 0;
  top: 0;
  pointer-events: none;
  opacity: 0;
  will-change: transform, opacity, scale;
}

.imt-stage.imt-static .imt-item {
  opacity: 1;
}

@media (prefers-reduced-motion: reduce) {
  .imt-stage:not(.imt-force) .imt-item {
    opacity: 1;
  }
}
```

JS（原生，不依赖任何库）：

```js
// 光标图片拖尾（Image trail）参考实现。
// 用法：容器 .imt-stage 内放若干 .imt-item 元素。
// 调 const ctl = imageTrail(stage, { threshold: 48, duration: 650, easing: '...' }); 销毁调 ctl.destroy()。

export function imageTrail(stage, {
  threshold = 48,
  duration = 650,
  easing = 'cubic-bezier(0.22, 1, 0.36, 1)',
  maxVisible = 6,
  ignoreReducedMotion = false,
} = {}) {
  if (!(stage instanceof Element)) return null;
  const items = [...stage.querySelectorAll('.imt-item')];
  if (!items.length) return null;

  const distMin = Number(threshold) || 48;
  const dur = Number(duration) || 650;
  const easeStr = String(easing);
  const reduceQuery = typeof matchMedia === 'function' ? matchMedia('(prefers-reduced-motion: reduce)') : null;
  const isReduced = () => Boolean(reduceQuery?.matches && !ignoreReducedMotion);

  stage.classList.add('imt-stage');
  stage.classList.remove('imt-static');
  if (ignoreReducedMotion) stage.classList.add('imt-force');

  let index = 0;
  let lastX = null;
  let lastY = null;
  let zTop = 1;
  let destroyed = false;
  const active = new Set();

  const spawn = (localX, localY) => {
    if (destroyed || isReduced()) return null;
    const item = items[index % items.length];
    index += 1;
    // 若同一节点还在播，先取消旧动画复用它
    item.getAnimations().forEach((a) => a.cancel());
    if (active.size >= maxVisible) {
      const oldest = active.values().next().value;
      if (oldest && oldest !== item) {
        oldest.getAnimations().forEach((a) => a.cancel());
        oldest.style.opacity = '0';
        active.delete(oldest);
      }
    }

    const w = item.offsetWidth || 64;
    const h = item.offsetHeight || 48;
    const tilt = ((index % 2 === 0 ? 1 : -1) * ((index % 3) + 2));
    item.style.left = `${Math.round(localX - w / 2)}px`;
    item.style.top = `${Math.round(localY - h / 2)}px`;
    item.style.rotate = `${tilt}deg`;
    item.style.zIndex = String(++zTop);
    active.add(item);

    const anim = item.animate(
      [
        { opacity: 1, scale: '0.75' },
        { opacity: 0, scale: '1' },
      ],
      { duration: dur, easing: easeStr, fill: 'none' },
    );
    anim.finished.then(() => {
      if (!destroyed) active.delete(item);
    }).catch(() => undefined);
    return item;
  };

  const onMove = (ev) => {
    if (destroyed || ev.pointerType === 'touch' || isReduced()) return;
    const rect = stage.getBoundingClientRect();
    const x = ev.clientX - rect.left;
    const y = ev.clientY - rect.top;
    if (lastX === null || lastY === null) {
      lastX = x;
      lastY = y;
      spawn(x, y);
      return;
    }
    if (Math.hypot(x - lastX, y - lastY) >= distMin) {
      lastX = x;
      lastY = y;
      spawn(x, y);
    }
  };

  const onLeave = () => {
    lastX = null;
    lastY = null;
  };

  stage.addEventListener('pointermove', onMove);
  stage.addEventListener('pointerleave', onLeave);

  return {
    spawn,
    activeCount: () => active.size,
    destroy() {
      if (destroyed) return;
      destroyed = true;
      stage.removeEventListener('pointermove', onMove);
      stage.removeEventListener('pointerleave', onLeave);
      stage.classList.remove('imt-force');
      items.forEach((el) => {
        el.getAnimations().forEach((a) => a.cancel());
        el.style.left = '';
        el.style.top = '';
        el.style.rotate = '';
        el.style.zIndex = '';
        el.style.opacity = '';
      });
      active.clear();
    },
  };
}
```

## 出处

- 第四批备选（竞品 2 家收录），本站按指针阈值采样与节点池复用方案自研实现，没有复制代码
