GSAP 與 ScrollTrigger 開發指南
概述
GSAP(GreenSock 動畫平台)是業界領先的 JavaScript 動畫函式庫,專為打造高效能、具備生產級品質的動畫而設計。ScrollTrigger 是 GSAP 的強大外掛,負責處理由捲動驅動的動畫。兩者結合,能實現從簡單的 UI 過場到複雜的捲動式敘事體驗等各種效果。
核心概念
基本元素:補間(Tween)
補間是從起點 A 到終點 B 的單一動畫。
// 動畫至某一狀態(從當前狀態開始)
gsap.to(".box", {
x: 200,
rotation: 360,
duration: 1,
ease: "power2.inOut"
});
// 從某一狀態開始動畫(到當前狀態)
gsap.from(".box", {
opacity: 0,
y: -50,
duration: 0.8
});
// 從某一狀態到另一狀態(同時定義起點與終點)
gsap.fromTo(".box",
{ opacity: 0, scale: 0.5 }, // 起點
{ opacity: 1, scale: 1, duration: 1 } // 終點
);
時間軸(Timeline):編排動畫序列
時間軸能依序或重疊地協調多個補間動畫。
const tl = gsap.timeline();
// 預設為依序執行
tl.to(".box1", { x: 100, duration: 1 })
.to(".box2", { y: 100, duration: 1 })
.to(".box3", { rotation: 360, duration: 1 });
// 使用標籤來組織
tl.addLabel("start")
.to(".hero", { opacity: 1, duration: 1 })
.addLabel("reveal")
.to(".content", { y: 0, duration: 0.8 }, "reveal") // 在 "reveal" 標籤處開始
.to(".cta", { scale: 1, duration: 0.5 }, "reveal+=0.5"); // 在 "reveal" 之後 0.5 秒
位置參數(時間軸內的時機控制)
控制動畫在時間軸內的起始時機:
const tl = gsap.timeline();
// 預設:一個接一個執行
tl.to(".box1", { x: 100 })
.to(".box2", { x: 100 }); // 在 box1 結束後開始
// 同時開始
tl.to(".box1", { x: 100 })
.to(".box2", { y: 100 }, 0); // 在第 0 秒開始
// 相對位置
tl.to(".box1", { x: 100, duration: 2 })
.to(".box2", { y: 100 }, "-=1"); // 在 box1 結束前 1 秒開始
.to(".box3", { rotation: 360 }, "+=0.5"); // 在 box2 結束後 0.5 秒開始
// 在指定時間
tl.to(".box1", { x: 100 }, 2.5); // 在第 2.5 秒開始
ScrollTrigger 基礎
基本捲動動畫
gsap.registerPlugin(ScrollTrigger);
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center", // 觸發元素的頂部對齊到視窗中央
end: "bottom center",
markers: true, // 僅開發時使用 - 顯示起點/終點位置
scrub: true, // 將動畫與捲軸連結
toggleActions: "play none none reverse" // onEnter onLeave onEnterBack onLeaveBack
}
});
起點與終點位置
格式:"[觸發位置] [視窗位置]"
// 常見模式
start: "top top" // 觸發頂部碰到視窗頂部
start: "top center" // 觸發頂部碰到視窗中央(預設)
start: "top bottom" // 觸發頂部碰到視窗底部
start: "center center" // 觸發中央碰到視窗中央
// 帶偏移量
start: "top top+=100" // 視窗頂部下方 100px
start: "top 80%" // 視窗往下 80%
end: "+=500" // 起點位置後 500px
end: "bottom top" // 觸發底部碰到視窗頂部
滾動同步(Scrub)
// 布林值:直接與捲軸連結(即時)
scrub: true
// 數字:平滑延遲秒數
scrub: 1 // 花 1 秒「追上」捲軸位置
scrub: 0.5 // 較快、更緊湊的觸感
觸發動作(Toggle Actions)
在四個捲動點控制動畫:
toggleActions: "play pause resume reset"
// onEnter | onLeave | onEnterBack | onLeaveBack
// 動作:play, pause, resume, restart, reset, complete, reverse, none
常見模式:
toggleActions: "play none none none" // 進入時播放一次
toggleActions: "play none none reverse" // 向前播放,向後倒轉
toggleActions: "play complete reverse reset" // 完全控制
toggleActions: "restart pause resume pause" // 每次進入時重新開始
常見模式
1. 捲動時淡入
gsap.from(".fade-in", {
opacity: 0,
y: 50,
duration: 1,
scrollTrigger: {
trigger: ".fade-in",
start: "top 80%",
end: "top 50%",
scrub: 1,
once: true // 僅動畫一次
}
});
2. 捲動時固定元素
ScrollTrigger.create({
trigger: ".panel",
start: "top top",
end: "+=500", // 固定 500px 的捲動距離
pin: true,
pinSpacing: true // 加入間距(預設為 true)
});
3. 水平捲動區段
const sections = gsap.utils.toArray(".panel");
gsap.to(sections, {
xPercent: -100 * (sections.length - 1),
ease: "none",
scrollTrigger: {
trigger: ".container",
pin: true,
scrub: 1,
end: () => "+=" + document.querySelector(".container").offsetWidth
}
});
4. 視差效果
// 較慢移動(背景層)
gsap.to(".bg", {
y: 200,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// 較快移動(前景層)
gsap.to(".fg", {
y: -100,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
5. 觸發式時間軸
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".container",
start: "top top",
end: "+=500",
scrub: 1,
pin: true,
snap: {
snapTo: "labels", // 對齊時間軸標籤
duration: { min: 0.2, max: 3 },
delay: 0.2,
ease: "power1.inOut"
}
}
});
tl.addLabel("start")
.from(".title", { scale: 0.3, rotation: 45, autoAlpha: 0 })
.addLabel("color")
.from(".box", { backgroundColor: "#28a92b" })
.addLabel("spin")
.to(".box", { rotation: 360 })
.addLabel("end");
6. 批次動畫(多個元素)
// 遍歷多個元素
gsap.utils.toArray(".box").forEach((box, i) => {
gsap.from(box, {
y: 100,
opacity: 0,
scrollTrigger: {
trigger: box,
start: "top 80%",
end: "top 50%",
scrub: 1
}
});
});
// 或使用 ScrollTrigger.batch
ScrollTrigger.batch(".box", {
onEnter: batch => gsap.to(batch, { opacity: 1, y: 0, stagger: 0.15 }),
onLeave: batch => gsap.set(batch, { opacity: 0 }),
start: "top 80%",
once: true
});
7. 階梯式動畫
gsap.from(".item", {
y: 50,
opacity: 0,
duration: 0.8,
stagger: 0.1, // 每個項目間隔 0.1 秒
scrollTrigger: {
trigger: ".grid",
start: "top 80%"
}
});
// 進階階梯效果
gsap.from(".item", {
scale: 0,
duration: 1,
stagger: {
each: 0.1,
from: "center", // "start", "center", "end", "edges" 或索引數字
grid: "auto", // 針對網格佈局
ease: "power2.inOut"
}
});
整合模式
與 Three.js / WebGL 整合
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
// 動畫相機
gsap.to(camera.position, {
x: 5,
y: 3,
z: 10,
scrollTrigger: {
trigger: "#section2",
start: "top top",
end: "bottom top",
scrub: 1,
onUpdate: () => camera.lookAt(scene.position)
}
});
// 動畫網格旋轉
gsap.to(mesh.rotation, {
y: Math.PI * 2,
scrollTrigger: {
trigger: "#section3",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// 動畫材質屬性
gsap.to(material, {
opacity: 0,
scrollTrigger: {
trigger: "#section4",
start: "top center",
end: "center center",
scrub: 1
}
});
與 React 整合(useGSAP 鉤子)
import { useRef } from 'react';
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
function Component() {
const container = useRef();
const box = useRef();
useGSAP(() => {
gsap.to(box.current, {
x: 200,
scrollTrigger: {
trigger: box.current,
start: "top center",
end: "bottom center",
scrub: true,
markers: true
}
});
}, { scope: container }); // 設定作用域以利清理
return (
<div ref={container}>
<div ref={box} className="box">動畫盒子</div>
</div>
);
}
在 React 中共用時間軸
function App() {
const [tl, setTl] = useState();
useGSAP(() => {
const timeline = gsap.timeline();
setTl(timeline);
}, []);
return (
<div>
<Box timeline={tl} index={0} />
<Circle timeline={tl} index={1} />
</div>
);
}
function Box({ timeline, index }) {
const ref = useRef();
useGSAP(() => {
timeline && timeline.to(ref.current, { x: 100 }, index * 0.1);
}, [timeline, index]);
return <div ref={ref} className="box" />;
}
Locomotive Scroll 整合
import LocomotiveScroll from 'locomotive-scroll';
const scroller = new LocomotiveScroll({
el: document.querySelector('[data-scroll-container]'),
smooth: true
});
ScrollTrigger.scrollerProxy("[data-scroll-container]", {
scrollTop(value) {
return arguments.length ? scroller.scrollTo(value, 0, 0) : scroller.scroll.instance.scroll.y;
},
getBoundingClientRect() {
return {top: 0, left: 0, width: window.innerWidth, height: window.innerHeight};
},
pinType: document.querySelector("[data-scroll-container]").style.transform ? "transform" : "fixed"
});
ScrollTrigger.addEventListener("refresh", () => scroller.update());
ScrollTrigger.refresh();
進階技巧
圖片序列滾動同步
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
const images = [];
const imageCount = 147;
const currentFrame = { value: 0 };
for (let i = 0; i < imageCount; i++) {
const img = new Image();
img.src = `./frames/frame_${i.toString().padStart(4, '0')}.jpg`;
images.push(img);
}
images[0].onload = () => {
canvas.width = images[0].width;
canvas.height = images[0].height;
render();
};
function render() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(images[Math.floor(currentFrame.value)], 0, 0);
}
gsap.to(currentFrame, {
value: imageCount - 1,
snap: "value",
ease: "none",
scrollTrigger: {
trigger: canvas,
start: "top top",
end: "+=500%",
scrub: true,
pin: true
},
onUpdate: render
});
平滑捲動到元素
gsap.registerPlugin(ScrollToPlugin);
// 捲動到元素
gsap.to(window, {
duration: 1,
scrollTo: "#section2",
ease: "power2.inOut"
});
// 帶偏移量
gsap.to(window, {
duration: 1.5,
scrollTo: { y: "#section2", offsetY: 50 },
ease: "expo.inOut"
});
// 水平捲動
gsap.to(".container", {
duration: 2,
scrollTo: { x: 1000, autoKill: true }
});
條件式動畫(媒體查詢)
ScrollTrigger.matchMedia({
// 桌面
"(min-width: 800px)": function() {
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center",
end: "bottom top",
scrub: true
}
});
},
// 行動裝置
"(max-width: 799px)": function() {
gsap.to(".box", {
y: 200,
scrollTrigger: {
trigger: ".box",
start: "top 80%",
scrub: 1
}
});
}
});
效能最佳實務
1. 使用 will-change CSS
.animated-element {
will-change: transform, opacity;
}
2. 限制重繪
// 良好:動畫 transform/opacity(GPU 加速)
gsap.to(".box", { x: 100, opacity: 0.5 });
// 避免:動畫佈局屬性
// gsap.to(".box", { width: 500, height: 300 }); // 會導致 reflow
3. 銷毀 ScrollTrigger
// 銷毀單一觸發
const trigger = ScrollTrigger.create({ /* ... */ });
trigger.kill();
// 銷毀所有觸發
ScrollTrigger.getAll().forEach(t => t.kill());
// 在 React 中搭配清理
useGSAP(() => {
const tween = gsap.to(".box", { /* ... */ });
return () => {
tween.kill();
};
}, []);
4. 防抖動調整大小
ScrollTrigger 會自動處理,但若需自訂調整邏輯:
let resizeTimer;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
ScrollTrigger.refresh();
}, 250);
});
5. 使用 invalidateOnRefresh
針對調整大小時會變動的動態值:
gsap.to(".box", {
x: () => window.innerWidth / 2, // 動態值
scrollTrigger: {
trigger: ".box",
start: "top center",
invalidateOnRefresh: true // 調整大小時重新計算 x
}
});
常見陷阱
1. 對同一元素使用多個補間
// 問題:第二個補間與第一個衝突
gsap.to('h1', { x: 100, scrollTrigger: { /* ... */ } });
gsap.to('h1', { x: 200, scrollTrigger: { /* ... */ } }); // 會跳動!
// 解法 1:使用 fromTo
gsap.fromTo('h1', { x: 100 }, { x: 200, scrollTrigger: { /* ... */ } });
// 解法 2:使用 immediateRender: false
gsap.to('h1', { x: 200, immediateRender: false, scrollTrigger: { /* ... */ } });
// 解法 3:將 ScrollTrigger 套用到時間軸
const tl = gsap.timeline({ scrollTrigger: { /* ... */ } });
tl.to('h1', { x: 100 })
.to('h1', { x: 200 });
2. 未針對多個元素使用迴圈
// 錯誤:一次動畫所有元素
gsap.to('.section', {
y: -100,
scrollTrigger: { trigger: '.section', scrub: true }
});
// 正確:為每個元素建立獨立觸發
gsap.utils.toArray('.section').forEach(section => {
gsap.to(section, {
y: -100,
scrollTrigger: { trigger: section, scrub: true }
});
});
3. 忘記註冊外掛
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';
gsap.registerPlugin(ScrollTrigger, ScrollToPlugin); // 務必註冊!
4. 忽略響應式設計
// 在行動裝置上優先考慮效能與簡潔動畫
ScrollTrigger.matchMedia({
"(min-width: 768px)": function() {
// 複雜桌面動畫
},
"(max-width: 767px)": function() {
// 較簡單的行動動畫
}
});
// 切勿使用 window.innerWidth 來判斷是否初始化
// 因為視窗大小會在裝置旋轉或重設大小時變動
5. 錯誤的觸發元素位置
// 若觸發元素並非 ScrollTrigger 建立時即在 DOM 中,
// 應於 DOMContentLoaded 或 useEffect 完成後再建立 ScrollTrigger
document.addEventListener("DOMContentLoaded", () => {
ScrollTrigger.create({
trigger: ".lazy-loaded-element",
/* ... */
});
});
疑難排解
動畫未播放
- 確認已使用
gsap.registerPlugin(ScrollTrigger)註冊 ScrollTrigger;若使用 ScrollToPlugin 亦須註冊。 - 確保 DOM 元素在建立 ScrollTrigger 時已存在;若為動態載入,請使用回呼或 React 的 useEffect。
- 若同時操作多個元素,請使用
gsap.utils.toArray()或ScrollTrigger.batch()。 - 檢查瀏覽器控制台是否有錯誤或警告,尤其是與 GSAP 相關的訊息。
- 驗證 CSS 是否有衝突,例如
overflow: hidden可能影響捲動行為。 - 使用
markers: true協助除錯,確認觸發位置是否正確。
動畫抖動或閃爍
- 切換至僅動畫
transform與opacity屬性,因為它們由 GPU 加速。 - 在即將動畫的元素上加入
will-change: transform, opacity。 - 避免對相同元素套用互相衝突的補間動畫。
- 使用
immediateRender: false或fromTo()來防止初始跳動。 - 檢查 CSS transition 是否干擾 GSAP 動畫。
捲動卡頓
- 減少同時啟動的 ScrollTrigger 實例數量。
- 對複雜的捲軸驅動動畫使用
scrub: 0.5而非scrub: true。 - 盡可能使用
pinSpacing: false,因為動態插入間距可能造成版面震盪。 - 善用
ScrollTrigger.normalizeScroll(true)改善觸控裝置的捲動效能。 - 限制捲動觸發的 DOM 操作(例如 reposition 或 resize),以維持流暢性。
在特定瀏覽器上失效
// 若在 iOS Safari 上捲動失效,嘗試:
ScrollTrigger.config({ ignoreMobileResize: true });
// 若與其他捲動函式庫(如 Lenis 或 Barba.js)整合,請使用 scrollerProxy。
資源
貢獻
歡迎對此技能提出改進建議。請提交 Pull Request 或開啟 Issue 以討論變更內容。
授權
本技能僅供教育與參考用途。GSAP 本身遵循 GreenSock 的標準授權條款。