与 GSAP 并行播放 2 个补间?

Mas*_*ffo 5 javascript animation timeline gsap

有人可以简要解释一下使用GSAP 3在同一时间线中并行播放 2 个补间/动画的最佳方式是什么?

例子:

tl = gsap.timeline();

tl
.to( 'EL1', 1, {
   prop: value,
})
.to( 'EL2', 1, {
   prop: value
}, '-=1');
Run Code Online (Sandbox Code Playgroud)

我会这样做:'-=1'。大家有更好的解决方案给我吗?

Zac*_*ier 8

首先,在 GSAP 3 中我们不建议使用持续时间参数。相反,我们建议在 vars 参数中包含持续时间,以便您可以使用 GSAP默认功能等功能。有关升级到 GSAP 3 的更多信息,请参阅迁移指南。为了回答这个问题,我在下面省略了持续时间。


有很多方法可以确保两个补间同时启动:

  1. 我经常发现最简单的方法是使用位置'<'参数运算符。这会导致补间从与最后一个补间相同的起始位置开始。例如:

    .to('EL1', { prop: value })
    .to('EL2', { prop: value }, '<')
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用标签。您可以通过多种方式创建标签:

    .to('EL1', { prop: value }, 'myLabel') // If the label doesn't exist, it will be created at the start of this tween
    .to('EL2', { prop: value }, 'myLabel') // Since the label exists already, this tween will be positioned with its start at the label
    
    Run Code Online (Sandbox Code Playgroud)

    或者显式创建它:

    .add('myLabel') // .addLabel() also works
    .to('EL1', { prop: value }, 'myLabel') // If the label doesn't exist, it will be created at the start of this tween
    .to('EL2', { prop: value }, 'myLabel') // Since the label exists already, this tween will be positioned with its start at the label
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用相对偏移量。仅当您还使用前一个补间的持续时间时,这才有效:

    .to('EL1', { prop: value })
    .to('EL2', { prop: value }, '-=1') // Assuming the duration of the previous tween is 1
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在时间线中使用明确的时间。我几乎只在希望补间从时间线开头开始时才使用此方法:

    .to('EL1', { prop: value })
    .to('EL2', { prop: value }, 0) // Number of seconds in the timeline to start at - can be any number
    
    Run Code Online (Sandbox Code Playgroud)
  5. 在某些情况下,您可能希望作为时间线的一部分同时触发多个预制动画。在这种情况下,您可能需要添加一个在特定时间触发这两个函数的函数,如下所示:

    .add(() => {
      myAnim1.play();
      myAnim2.play();
    })
    
    Run Code Online (Sandbox Code Playgroud)

    请注意,这种方法实际上并没有将补间添加到时间轴,它只是使用时间轴一部分的函数来播放动画。

    您可以使用两个单独的调用将补间本身添加到时间轴中.add()。如果您想将预制动画排序为时间线的一部分,这也是您应该执行的操作。要定位它们,请使用上面其他点中介绍的相同方法。

    .add(myAnim1)
    .add(myAnim2, '<')
    
    Run Code Online (Sandbox Code Playgroud)

有关更多说明,请参阅位置参数帖子