# 鼠标视差 Mouse Parallax > 首屏插画分成几层,跟着鼠标往反方向各走各的距离,看起来有纵深。 分类:鼠标特效 · 角色:主角(占一整块、抢全部注意力,一页最多一个) [全部组件和流程](https://www.dachuiai.com/llms.txt) · [鼠标特效选型规则](https://www.dachuiai.com/guides/cursor.md) ## 给 AI:用户把这个组件发给了你 1. 先看用户的项目:框架、页面类型、现在的风格、手机还是电脑为主。 2. 对照下面的「适合 / 不适合」判断合不合适。不合适就直接说,并从[鼠标特效选型规则](https://www.dachuiai.com/guides/cursor.md)或[全部组件](https://www.dachuiai.com/llms.txt)里另挑一个。 3. 合适就按「装进项目」装好,示例里的文字和图片换成用户自己的。 4. 告诉用户用了什么、放在哪个文件、以后想改快慢、颜色、大小改哪个参数。 ## 什么时候用 - 适合:旅行、户外、游戏、品牌官网的首屏,有能分层的插画或照片(天空、远山、近景)。 - 不适合:只有一张平面图(分不出层);后台和内容站;同一屏已经有跟着滚动走的视差(parallax)。 - 适合的网站:官网、活动页、作品集 - 放在:首屏 - 手机上:没效果:手机上画面不动。 - 性能代价:低:几层 transform,没在动就停。 - 常搭配:[滚动出现 Scroll Reveal](https://www.dachuiai.com/c/scroll-reveal.md)、[磁吸 Magnetic](https://www.dachuiai.com/c/magnetic.md) ## 装进项目 - 写法:React 18 以上 + TypeScript + Tailwind CSS v4,一个文件就能用,不引用别的组件。 - 依赖:只用 react,不用另外安装 - 文件:原样存成 `mouse-parallax.tsx`(比如 `src/components/mouse-parallax.tsx`)。能跑命令就下载[原文](https://www.dachuiai.com/code/mouse-parallax.tsx),比手抄准:`curl -fsSL -o src/components/mouse-parallax.tsx https://www.dachuiai.com/code/mouse-parallax.tsx`(Windows 写 `curl.exe`)。下载完看一眼第一行是 `import`,不是网页。 - 导出:`MouseParallax` 是可以直接用的部分;最后的 `export default` 是演示示例,只作参考。 - 注意:每层写 data-depth(最多移动几像素),并且要比区域大一圈(比如 -inset-10),移动时边上才不露底。 - 保留代码里 `prefers-reduced-motion` 的处理:用户开了「减弱动态效果」时内容照样完整显示。 - Next.js(有 app 文件夹):文件第一行加 `'use client';`。 - 用 JavaScript 不用 TypeScript:Vite 和 Next.js 都能直接用 .tsx 文件;也可以删掉类型标注,改名 .jsx。 - 没有 Tailwind:先装 Tailwind CSS v4(Vite 项目 `npm i tailwindcss @tailwindcss/vite`,vite 配置的 plugins 里加 `tailwindcss()`,入口引入的那个 CSS 文件(一般是 `src/index.css`)第一行写 `@import "tailwindcss";`),或者把类名改写成项目用的样式。 - 已经装了 Tailwind v3:别为了一个组件升级。类名大多通用,少数 v4 写法要换,比如焦点框 `outline-2` 在 v3 里要写成 `outline outline-2`。 - 不是 React(Vue、Svelte、小程序、纯 HTML):照着代码的做法改写,时长、曲线、参数保持一样。Wix、有赞这类建站平台装不进代码,告诉用户去平台自带的动效设置里找。 ## 参数 | 参数 | 默认值 | 作用 | | --- | --- | --- | | `children` | | 包在里面的内容 | | `ease` | `5.5` | 跟随的快慢,越大跟得越紧 | | `className` | `''` | 加在最外层的类名,用来调大小、位置、间距 | ## 你可以说 > 首屏插画分成 4 层:按鼠标离中心的偏移移动每一层,最近的最多 30 像素,最远的 6 像素,带缓动跟随。 ## 完整代码 ```tsx import {useEffect, useMemo, useRef, type ReactNode} from 'react'; /* --------------------------------------------------------------- * MouseParallax 鼠标视差 * 首屏插画分成几层:按鼠标离中心的偏移,每层往反方向移动不同的距离,远的动得少、近的动得多,带缓动跟随,看起来有纵深。 * 里面的元素写 data-depth="数字":鼠标在区域边上时这一层最多横着移动多少像素(上下只动一半)。 * 每层要比区域大一圈(比如 inset: -40px),移动时边上才不会露底。没在动的时候就停下,不占动画。 * 只在有鼠标的设备上动;手机、平板和开了「减弱动态效果」时画面不动。 * ease:跟随的快慢,越大跟得越紧 * ------------------------------------------------------------- */ type Props = {children: ReactNode; ease?: number; className?: string}; export function MouseParallax({children, ease = 5.5, className = ''}: Props) { const root = useRef(null); useEffect(() => { if (!matchMedia('(pointer: fine)').matches || matchMedia('(prefers-reduced-motion: reduce)').matches) return; const el = root.current!; const layers = [...el.querySelectorAll('[data-depth]')].map((n) => ({n, d: Number(n.dataset.depth) || 0, x: 0, y: 0})); const m = {x: 0, y: 0}; let raf = 0, prev = 0; const frame = (now: number) => { const dt = Math.min(0.05, Math.max(0, now - prev) / 1000), k = 1 - Math.exp(-ease * dt); prev = now; let moving = false; for (const l of layers) { const tx = -m.x * l.d, ty = -m.y * l.d * 0.5; l.x += (tx - l.x) * k; l.y += (ty - l.y) * k; if (Math.abs(tx - l.x) + Math.abs(ty - l.y) > 0.02) moving = true; l.n.style.transform = `translate3d(${l.x.toFixed(2)}px, ${l.y.toFixed(2)}px, 0)`; } raf = moving ? requestAnimationFrame(frame) : 0; }; const kick = () => { if (!raf) { prev = performance.now(); raf = requestAnimationFrame(frame); } }; const move = (e: PointerEvent) => { if (e.pointerType === 'touch') return; const r = el.getBoundingClientRect(); m.x = ((e.clientX - r.left) / r.width - 0.5) * 2; m.y = ((e.clientY - r.top) / r.height - 0.5) * 2; kick(); }; const leave = () => { m.x = 0; m.y = 0; kick(); }; el.addEventListener('pointermove', move); el.addEventListener('pointerleave', leave); return () => { cancelAnimationFrame(raf); el.removeEventListener('pointermove', move); el.removeEventListener('pointerleave', leave); for (const l of layers) l.n.style.transform = ''; }; }, [ease]); return
{children}
; } /* ---------------- 示例:户外旅行网站的首屏(黄昏山景,全部代码画的) ---------------- */ const SERIF = '"Noto Serif SC", "Source Han Serif SC", "Songti SC", "STSong", serif'; const GROTESK = '"Space Grotesk", "SF Pro Display", ui-sans-serif, system-ui, sans-serif'; const VW = 1080, VH = 720; // 每层自己的画布:比舞台大一圈,移动时不露底 const rng = (seed: number) => () => { seed = (seed + 0x6d2b79f5) >>> 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; // 山脊线:几条正弦波叠起来 const ridge = (base: number, waves: [number, number][], seed: number) => { const r = rng(seed), ph = waves.map(() => r() * 7); return (x: number) => base + waves.reduce((a, [amp, f], i) => a + amp * Math.sin(x * f + ph[i]), 0); }; const fillPath = (f: (x: number) => number) => { let d = `M0 ${VH}L0 ${f(0).toFixed(1)}`; for (let x = 8; x <= VW; x += 8) d += `L${x} ${f(x).toFixed(1)}`; return `${d}L${VW} ${VH}Z`; }; const layer = 'absolute -inset-10 will-change-transform'; function Landscape() { const art = useMemo(() => { const far = ridge(376, [[33, 0.0086], [16, 0.0236], [6.5, 0.057], [3, 0.125]], 3); const mid = ridge(462, [[39, 0.0067], [19, 0.0182], [7, 0.046], [3.6, 0.099]], 8); const near = ridge(590, [[22, 0.0057], [10, 0.0157], [3.6, 0.042]], 5); // 近处的山坡:高低不一的松树,中间留一块空地放小木屋 const r = rng(21); let pines = ''; for (let x = 14; x < VW; x += 16 + r() * 32) { if (x > 640 && x < 800) continue; const h = 50 + r() * 94, w = h * (0.3 + r() * 0.08), y = near(x) + 4; let p = `M${x - 2} ${y}L${x - 2} ${y - h * 0.2}`; for (let k = 0; k < 4; k++) { const yy = y - h * (0.16 + k * 0.2), ww = (w * (1 - k * 0.2)) / 2; p += `L${x - ww} ${yy}L${x - ww * 0.36} ${yy - h * 0.2}`; } p += `L${x} ${y - h}`; for (let k = 3; k >= 0; k--) { const yy = y - h * (0.16 + k * 0.2), ww = (w * (1 - k * 0.2)) / 2; p += `L${x + ww * 0.36} ${yy - h * 0.2}L${x + ww} ${yy}`; } pines += `${p}L${x + 2} ${y - h * 0.2}L${x + 2} ${y}Z`; } return {far: fillPath(far), mid: fillPath(mid), near: fillPath(near), pines, cabin: near(720), walker: near(668)}; }, []); return ( <>
{[['8%', '47%', '34%', 1], ['52%', '41%', '40%', 0.7], ['30%', '62%', '26%', 0.8]].map(([l, t, w, o]) => (
))}

去更远的地方

每个周末,一条新的山路

{/* 亮着灯的小木屋,旁边一个人在看风景 */}
); } export default function MouseParallaxDemo() { return ( e.preventDefault()} className="absolute bottom-10 left-1/2 inline-flex h-[52px] -translate-x-1/2 items-center whitespace-nowrap rounded-full bg-[#FFE9C8] px-8 text-[17px] font-extrabold text-[#2A1838] shadow-[0_16px_36px_rgba(20,10,30,.45)] outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-[#2A1838]">开始探索 → ); } ```