GSAP
简介
GSAP(GreenSock Animation Platform)是一个高性能、功能强大的 JavaScript 动画库,广泛应用于 Web 动画开发。它支持补间动画、时间线控制、SVG/CSS/JS 属性动画等,兼容性极佳。
安装
1. 使用 npm 安装
npm install gsap
2. CDN 引入
<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>
<!-- 插件 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ScrollTrigger.min.js"></script>
基础用法
对一个元素应用动画
<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>
<div class="box" style="width:50px;height:50px;background:#4caf50;"></div>
gsap.fromTo(
".box",
{
rotation: 0,
},
{
rotation: 360,
duration: 1,
ease: "none",
repeat: -1,
}
);
2. from/to/fromTo
gsap.to()
:从当前状态到目标状态gsap.from()
:从指定初始状态到当前状态gsap.fromTo()
:自定义起始和结束状态
<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>
<div class="box" style="width:50px;height:50px;background:#4caf50;"></div>
gsap.from(".box", { opacity: 0, y: 50, duration: 1 });
gsap.fromTo(".box", { scale: 0 }, { scale: 1, duration: 1 });
常用 API 示例
- duration:动画持续时间
- repeat:重复次数
- yoyo:往返动画
- ease:缓动函数
- x:水平位移
- y:垂直位移
- rotation:旋转角度
- scale:缩放比例
- opacity:透明度
- delay:动画延迟时间
gsap.to(".box", {
x: 200,
duration: 2,
delay: 0.5,
repeat: 1,
yoyo: true,
ease: "power1.inOut",
});
时间线
GSAP 的 Timeline(时间线)可以让多个动画顺序或并行执行,便于复杂动画编排。
const tl = gsap.timeline();
tl.to(".box", { x: 100, duration: 1 }).to(".box", { y: 100, duration: 1 }).to(".box", { rotation: 360, duration: 1 });
插件
滚动插件 ScrollTrigger
<div class="container">
<div class="box">
<div class="item">⚙️</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/gsap@3/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ScrollTrigger.min.js"></script>
gsap.registerPlugin(ScrollTrigger);
gsap.fromTo(
".item",
{
x: 0,
},
{
x: (() => {
const width = document.documentElement.clientWidth - 26 - 16;
return width;
})(),
ease: "none",
duration: 1,
scrollTrigger: {
trigger: '.item',
scrub: true,
pin: true,
start: "top top",
end: () => `+=${document.body.scrollHeight - window.innerHeight}`,
},
}
);
.container {
height: 200px;
}
.box {
height: 1000px;
border: 1px solid #000;
overflow: auto;
}
.item {
width: 26px;
height: 26px;
}