GSAP 动画库入门指南
GSAP (GreenSock Animation Platform) 是一个强大的 JavaScript 动画库,用于创建高性能的网页动画。本文将介绍 GSAP 的基础用法和核心概念。
1. 基础动画方法 ⚡
GSAP 提供了四个核心动画方法:
- 🎯
gsap.to(): 从当前状态过渡到目标状态 - 🎯
gsap.from(): 从设定状态过渡到当前状态 - 🎯
gsap.fromTo(): 在两个自定义状态间过渡 - 🎯
gsap.set(): 立即设置状态(无动画)
js
// 基础示例
gsap.to(".box", { x: 100, duration: 1 }); // 向右移动100px
gsap.from(".box", { opacity: 0, y: 50 }); // 淡入上移动画
gsap.fromTo(".box",
{ x: -100, opacity: 0 },
{ x: 0, opacity: 1 }
); // 从左侧淡入2. 选择器与目标元素 🎯
GSAP 支持多种选择器方式:
js
// CSS 选择器
gsap.to(".box", { x: 200 });
gsap.to("#unique", { x: 200 });
// DOM 元素
const element = document.querySelector(".box");
gsap.to(element, { x: 200 });
// 多个元素
gsap.to([".box1", ".box2"], { x: 200 });3. 动画属性配置 ⚙️
3.1 常用属性
js
gsap.to(".box", {
// 变换属性
x: 100, // translateX
y: 50, // translateY
rotation: 360, // 旋转角度
scale: 1.5, // 缩放
// 动画控制
duration: 1, // 动画时长(秒)
delay: 0.5, // 延迟开始
ease: "power2.inOut", // 缓动函数
repeat: -1, // 重复次数(-1为无限循环)
yoyo: true, // 往返动画
// 回调函数
onStart: () => console.log("开始"),
onComplete: () => console.log("完成"),
onUpdate: () => console.log("更新")
});3.2 特殊单位使用
js
gsap.to(".box", {
x: "+=100", // 相对移动
x: "50vw", // 视窗单位
rotation: "1.25rad" // 弧度单位
});4. 时间线动画 ⏱️
时间线(Timeline)用于编排复杂的动画序列:
js
const tl = gsap.timeline({
defaults: { duration: 1 }, // 默认配置
repeat: -1, // 整体重复
yoyo: true // 整体往返
});
// 按序添加动画
tl.to(".box1", { x: 100 })
.to(".box2", { x: 100 }, "<") // 与前一个同时
.to(".box3", { x: 100 }, "+=0.5") // 间隔0.5秒
.to(".box4", { x: 100 }, "myLabel") // 使用标签4.1 位置参数说明 📍
"<"- 与前一个动画同时开始">"- 接续前一个动画结束"+= 1"- 等待1秒后开始"-= 1"- 提前1秒开始"25%"- 在时间线25%处开始
5. 动画控制方法 🎮
js
const tween = gsap.to(".box", { x: 100 });
// 控制方法
tween.play(); // 播放
tween.pause(); // 暂停
tween.resume(); // 继续
tween.reverse(); // 反向
tween.restart(); // 重新开始
tween.timeScale(2); // 2倍速播放6. 实用技巧 💡
- 性能优化
js
// 使用 transform 代替位置属性
gsap.to(".box", { x: 100 }); // 优于 left: 100- 组合动画
js
gsap.to(".box", {
x: 100,
scale: 1.2,
backgroundColor: "#ff0000",
duration: 1
});- 随机值
js
gsap.to(".box", {
x: "random(-100, 100)", // 随机位置
rotation: "random([0, 90, 180, 270])" // 随机角度
});注意事项 ⚠️
- 避免在动画中使用耗性能的属性(如 width/height)
- 使用 will-change 提升动画性能
- 及时清理不需要的动画实例
- 合理使用 timeline 管理复杂动画
- 注意动画的兼容性问题