GSAP
概述
GSAP (GreenSock Animation Platform) 是最強大的網頁動畫函式庫。能處理複雜時間軸、滾動驅動動畫、SVG 變形、文字效果與基於物理的運動。被 Apple、Google、Nike 用於登陸頁面和產品展示。大多數情況下免費使用。
使用說明
步驟 1:基本動畫
import gsap from 'gsap'
// 動畫到目標狀態
gsap.to('.hero-title', { opacity: 1, y: 0, duration: 1, ease: 'power3.out' })
// 從指定狀態開始動畫
gsap.from('.card', { opacity: 0, y: 50, duration: 0.8, stagger: 0.15 })
// 立即設定
gsap.set('.hidden-element', { opacity: 0, y: 20 })
步驟 2:時間軸
// 序列化動畫 — 依次播放
const tl = gsap.timeline({ defaults: { duration: 0.6, ease: 'power2.out' } })
tl.from('.logo', { scale: 0, rotation: -180 })
.from('.nav-link', { opacity: 0, y: -20, stagger: 0.1 }, '-=0.3') // 重疊 0.3 秒
.from('.hero-text', { opacity: 0, x: -50 })
.from('.cta-button', { opacity: 0, scale: 0.8 }, '<') // 與前一個同時開始
// 控制
tl.play()
tl.reverse()
tl.pause()
tl.seek(1.5) // 跳至 1.5 秒處
步驟 3:ScrollTrigger
import { ScrollTrigger } from 'gsap/ScrollTrigger'
gsap.registerPlugin(ScrollTrigger)
// 當滾動到可視區域時播放動畫
gsap.from('.feature-section', {
scrollTrigger: {
trigger: '.feature-section',
start: 'top 80%', // 當元素頂部碰到視口 80% 時觸發
end: 'bottom 20%',
toggleActions: 'play none none reverse', // 進入、離開、再進入、再離開
},
opacity: 0,
y: 100,
duration: 1,
})
// 滾動時固定區段
gsap.to('.horizontal-section', {
x: () => -(document.querySelector('.horizontal-section').scrollWidth - window.innerWidth),
scrollTrigger: {
trigger: '.horizontal-wrapper',
pin: true,
scrub: 1, // 平滑拖曳 (1 秒延遲)
end: () => '+=' + document.querySelector('.horizontal-section').scrollWidth,
},
})
步驟 4:React 整合
import { useRef } from 'react'
import { useGSAP } from '@gsap/react'
import gsap from 'gsap'
function AnimatedSection() {
const container = useRef(null)
useGSAP(() => {
gsap.from('.card', {
opacity: 0, y: 40, stagger: 0.1, duration: 0.6,
scrollTrigger: { trigger: container.current, start: 'top 80%' },
})
}, { scope: container })
return (
<div ref={container}>
<div className="card">卡片 1</div>
<div className="card">卡片 2</div>
<div className="card">卡片 3</div>
</div>
)
}
使用指南
- GSAP 對公開網站免費。商業外掛 (MorphSVG, SplitText) 需要授權。
- 在 React 中使用
useGSAPHook — 它會在元件卸載時自動清理動畫。 - 結合
scrub的 ScrollTrigger 可建立與滾動連結的動畫 (視差、進度條效果)。 stagger依序對多個元素執行動畫 — 比手動延遲更簡潔。- 對於複雜序列,GSAP 效能優於 CSS 動畫 — 基於 requestAnimationFrame。