入门GASP动画(2)—— 时间线、补间动画

1,291 阅读3分钟

原文来自:greensock.com/get-started…

建议去原文查看Demo,会更容易理解。

Timelines 时间线

时间线让我们可以创建可调整的、有弹性的动画序列。下面是一个包含三个补间的简单时间轴。默认情况下,内容会被添加到最后,所以它们会一个接一个地播放。

// 创建一个时间线
let tl = gsap.timeline()

// 将补间动画添加到时间轴上——注意我们使用的是tl.to,不是gsap.to
tl.to(".green", { x: 600, duration: 2 });
tl.to(".purple", { x: 600, duration: 1 });
tl.to(".orange", { x: 600, duration: 1 });

Position Parameter 位置参数

位置参数,是建立华丽的序列与精确的定时的秘密。

let tl = gsap.timeline()

// 从时间轴上1秒开始(时间轴的绝对位置)
tl.to(".green", { x: 600, duration: 2 }, 1);

// 在上一个动画的开始处插入
tl.to(".purple", { x: 600, duration: 1 }, "<");

// 在时间线结束后1秒处插入(一个间隔时间)
tl.to(".orange", { x: 600, duration: 1 }, "+=1");

我们可以使用指针、绝对时间、百分比和相对值的组合来定位几乎任何地方的补间!

位置参数的详细文档

Special Properties 特殊属性

时间线上的补间动画共享大部分的特殊属性,比如 repeat、dalay,允许你从整体上控制整个动画序列。

let tl = gsap.timeline({repeat: -1, repeatDelay: 1, yoyo: true})

tl.to(".green", { rotation: 360 });
tl.to(".purple", { rotation: 360 });
tl.to(".orange", { rotation: 360 });

Timeline Defaults 时间线默认值

如果您发现自己一遍又一遍地输入一个属性,那么可能是时候使用默认值了。任何添加在时间线上的默认值,将被由to()、from()和fromTo()等方法创建的所有子对象继承。这是保持代码简洁的好方法。

var tl = gsap.timeline({defaults: {duration: 1}});

//no more repetition of duration: 1!
tl.to(".green", {x: 200})
  .to(".purple", {x: 200, scale: 0.2})
  .to(".orange", {x: 200, scale: 2, y: 20});

Control methods 控制动画

到目前为止,我们所看到的所有动画都是在页面加载或延迟后播放的。但是如果你想对你的动画有更多的控制呢?一个常见的用例是在某个交互(如按钮点击或悬停)上播放动画。控制方法可以在补间和时间线上使用,并允许您播放,暂停,反转甚至加速您的动画!

// store the tween or timeline in a variable
let tween = gsap.to("#logo", {duration: 1, x: 100});

//pause
tween.pause();

//resume (honors direction - reversed or not)
tween.resume();

//reverse (always goes back towards the beginning)
tween.reverse();

//jump to exactly 0.5 seconds into the tween
tween.seek(0.5);

//jump to exacty 1/4th into the tween's progress:
tween.progress(0.25);

//make the tween go half-speed
tween.timeScale(0.5);

//make the tween go double-speed
tween.timeScale(2);

//immediately kill the tween and make it eligible for garbage collection
tween.kill();

Callbacks 回调

如果你需要知道动画何时开始,或者在动画结束时运行一些JS,你可以使用回调。所有的渐变和时间线都有这些回调:

  • onComplete:动画完成时调用。

  • onStart:动画开始时调用

  • onUpdate:每次动画更新时调用(动画处于活动状态时的每一帧)。

  • onRepeat:每次动画重复时调用。

  • onReverseComplete:当动画在反转时再次到达开始时调用。

Plugins 插件

现在你已经掌握了核心概念,插件是一个伟大的方式来提升你的动画超能力!只需要一点点代码和GSAP的ScrollTrigger,你就可以将你的渐变和时间线连接起来滚动……

Club GreenSock

Resources