SuperAPI AI 工具集

gsap-timeline

设计与创作

查看项目

更新于 10-15 08:33

技能介绍

用途

GSAP Timeline 技能适用于构建多步骤动画、协调多个补间按顺序或并行播放,或当用户询问 GSAP 中的时间线、序列编排、关键帧式动画时使用。

相关技能:单个补间与缓动使用 gsap-core;滚动驱动的时间线使用 gsap-scrolltrigger;React 中使用 gsap-react。

创建时间线

const tl = gsap.timeline();
tl.to(".a", { x: 100, duration: 1 })
  .to(".b", { y: 50, duration: 0.5 })
  .to(".c", { opacity: 0, duration: 0.3 });

默认情况下,补间会一个接一个地追加。使用位置参数可将补间放到特定时间,或相对于其他补间的位置。

位置参数

第三个参数(或 vars 中的 position 属性)控制放置位置:

  • 绝对值:1 — 在 1 秒处开始。
  • 相对值(默认):"+=0.5" — 在前一个结束之后 0.5 秒;"-=0.2" — 在前一个结束之前 0.2 秒。
  • 标签:"labelName" — 在该标签处;"labelName+=0.3" — 在标签之后 0.3 秒。
  • 放置:"<" — 与最近添加的动画同时开始;">" — 在最近添加的动画结束时开始(默认);"<0.2" — 在最近添加的动画开始之后 0.2 秒。

示例:

tl.to(".a", { x: 100 }, 0);           // at 0
tl.to(".b", { y: 50 }, "+=0.5");      // 0.5s after last end
tl.to(".c", { opacity: 0 }, "<");     // same start as previous
tl.to(".d", { scale: 2 }, "<0.2");    // 0.2s after previous start

时间线默认值

把 defaults 传入时间线,让所有子补间继承:

const tl = gsap.timeline({ defaults: { duration: 0.5, ease: "power2.out" } });
tl.to(".a", { x: 100 }).to(".b", { y: 50 }); // both use 0.5s and power2.out

时间线选项(构造函数)

  • paused: true — 创建时暂停;调用 .play() 开始。
  • repeat、yoyo — 与补间相同;作用于整个时间线。
  • onComplete、onStart、onUpdate — 时间线级别的回调。
  • defaults — 合并进每个子补间的 vars。

标签

添加并使用标签,让序列编排更可读、易维护:

tl.addLabel("intro", 0);
tl.to(".a", { x: 100 }, "intro");
tl.addLabel("outro", "+=0.5");
tl.to(".b", { opacity: 0 }, "outro");
tl.play("outro");  // start from "outro"
tl.tweenFromTo("intro", "outro"); // pauses the timeline and returns a new Tween that animates the timeline's playhead from intro to outro with no ease.

嵌套时间线

时间线可以包含其他时间线。

const master = gsap.timeline();
const child = gsap.timeline();
child.to(".a", { x: 100 }).to(".b", { y: 50 });
master.add(child, 0);
master.to(".c", { opacity: 0 }, "+=0.2");

播放控制

  • tl.play() / tl.pause()
  • tl.reverse() / tl.progress(1) 然后 tl.reverse()
  • tl.restart() — 从头开始。
  • tl.time(2) — 跳转到 2 秒。
  • tl.progress(0.5) — 跳转到 50%。
  • tl.kill() — 销毁时间线,默认也销毁其子级。

GSAP 官方最佳实践

  • ✅ 序列编排优先使用时间线
  • ✅ 使用位置参数(第三个参数)将补间放到特定时间,或相对于标签放置
  • ✅ 用 addLabel() 添加标签,让序列更可读、易维护
  • ✅ 把 defaults 传入时间线构造函数,让子补间继承 duration、ease 等
  • ✅ 把 ScrollTrigger 放在时间线(或顶层补间)上,而不是时间线内部的补间上

不要

  • ❌ 当时间线可以编排动画时,不要用 delay 串联动画;多步骤动画应优先使用 gsap.timeline() 和位置参数
  • ❌ 当多个子补间共享相同的 duration 或 ease 时,不要忘记传 defaults(例如 defaults: { duration: 0.5, ease: "power2.out" })
  • ❌ 不要忘记时间线构造函数上的 duration 与补间的 duration 不同;时间线的“duration”由其子级决定
  • ❌ 不要嵌套包含 ScrollTrigger 的动画;ScrollTrigger 只应放在顶层 Tween/Timeline 上