跳过主要内容

时间轴

快速入门

最简用法

// This is a Tween
gsap.to(".box", { rotation: 27, x: 100, duration: 1 });

// And this is a Timeline, containing three sequenced tweens
let tl = gsap.timeline();
tl.to("#green", {duration: 1, x: 786})
.to("#blue", {duration: 2, x: 786})
.to("#orange", {duration: 1, x: 786})

返回值:时间轴

A 时间轴是一个强大的序列化工具,可作为补间动画和其他时间轴的容器,使您能够轻松地整体控制它们,并精确管理它们的时间。如果没有时间轴,构建复杂的动画序列将会更加繁琐,因为您必须为每个动画使用delay延迟参数

// WITHOUT Timelines (only using delays):
gsap.to("#id", { x: 100, duration: 1 });
gsap.to("#id", { y: 50, duration: 2, delay: 1 }); //wait 1 second
gsap.to("#id", { opacity: 0, duration: 1, delay: 3 }); //wait 3 seconds

如果你想让第一个动画更长一些怎么办?你需要调整每一个后续的延迟。如果你想pause()播放整个序列或者restart()暂停它或者reverse()在播放时调整它,或者重复两次呢?这可能会变得非常混乱,但GSAP的时间轴让它变得异常简单:

0
1
2blueSpin
3
4
// then we can control the whole thing easily...
tl.pause();
tl.resume();
tl.seek(1.5);
tl.reverse();

现在我们可以调整时间而不用担心延迟的级联更改!增加第一个补间的持续时间,所有内容都会自动调整。

在时间线中定位动画

构建精美复杂动画的秘密在于理解position参数位置参数vars它被用于许多不同的时间轴方法中。这个超级灵活的参数控制着你的补间动画、标签、回调函数、暂停甚至嵌套时间轴的位置插入点。换句话说,它告诉时间轴确切地在哪里插入动画。它通常跟在

  • Absolute time, like 3参数(变量对象)
//insert exactly 3 seconds from the start of the timeline
tl.to(".class", { x: 100 }, 3);
  • 相对时间,例如"+=1"或者"-=1"(相对于时间轴的end开始)
//create a gap (insert 1 second after end of timeline)
tl.to(".class", { x: 100 }, "+=1");

//overlap end by 1 second
tl.to(".class", { y: 100 }, "-=1");
  • 标签,例如"someLabel"
//insert at the "someLabel" label (if it doesn't exist yet, it gets added to the end of the timeline)
tl.to(".class", { x: 100 }, "someLabel");
  • 相对于某个标签,例如"someLabel+=1"
//insert 2 seconds after the "someLabel" label
tl.to(".class", { x: 100 }, "someLabel+=2");
  • 插入到最近添加的动画的start开始位置,"<"
//insert at the START of the most recently added animation
tl.to(".class", { x: 100 }, "<");
  • 插入到最近添加的动画的end结束位置,">"
//insert at the END of the most recently added animation
tl.to(".class", { x: 100 }, ">");
  • 相对于最近添加的动画的开始位置,例如"<1"
//insert 1 second after the START of the most recently added animation
tl.to(".class", { x: 100 }, "<1");

//insert 2 seconds before the START of the most recently added animation (negative number)
tl.to(".class", { y: 100 }, "<-2");
  • 相对于最近添加的动画的结束位置,例如">1"
//insert 1 second after the END of the most recently added animation
tl.to(".class", { x: 100, duration: 1 }, ">1");

//insert 2 seconds before the END of the most recently added animation (negative number)
tl.to(".class", { y: 100, duration: 1 }, ">-2");

提示:将"<"">"视为指向最近添加动画的开始或结束的指针。

特殊属性和回调函数

将以下任意一个添加到您的vars对象中,以赋予动画特殊功能:

gsap.timeline({
onComplete: myFunction,
repeat: 2,
repeatDelay: 1,
yoyo: true,
});

所有时间轴的vars属性描述如下:

    属性

    描述

  • autoRemoveChildren

    Boolean如果autoRemoveChildren设置为true,一旦子补间动画/时间轴完成,它们将自动被销毁/移除。这通常是不理想的,因为它会阻止时间倒退(比如你想要reverse()反向播放autoRemoveChildren: true.
  • callbackScope

    对象用于所有回调函数(onStart, onUpdate, onCompleteonStart, onComplete等)的作用域。作用域是回调函数内部this所指向的对象。this refers to inside any of the callbacks.
  • defaults

    对象一种简单设置默认值的方式,这些值会被子动画继承。详见“defaults”部分。
  • delay

    数字动画开始前的延迟时间(秒)。
  • onComplete

    函数动画完成后应调用的函数。
  • onCompleteParams

    数组要传递给onCompleteonUpdategsap.timeline({onComplete: myFunction, onCompleteParams: ["param1", "param2"]});.
  • onInterrupt

    动画中断时要调用的函数。注意:如果动画正常完成则不会触发此函数。
  • onInterruptParams

    要传递给onInterrupt函数的参数数组。例如,gsap.to(".class", {x:100, onInterrupt:myFunction, onInterruptParams:["param1", "param2"]});.
  • onRepeat

    函数动画每次重复时应调用的函数。
  • onRepeatParams

    数组要传递给onRepeatonUpdategsap.timeline({onRepeat: myFunction, onRepeatParams: ["param1", "param2"]});.
  • onReverseComplete

    函数当动画从反方向回到其开始位置时应调用的函数。例如,如果reverse()reverse()time reaches 0, onReverseComplete回调将被调用。当动画放置在一个被反转播放的时间轴实例中并反向播放到(或超过)起始位置时也会发生这种情况。
  • onReverseCompleteParams

    数组要传递给onReverseCompleteonUpdategsap.timeline({onReverseComplete: myFunction, onReverseCompleteParams: ["param1", "param2"]});.
  • onStart

    函数当动画开始时(当它的timeprogress0从0
  • onStartParams

    数组要传递给onStartonUpdategsap.timeline({onStart: myFunction, onStartParams: ["param1", "param2"]});.
  • onUpdate

    函数每次动画更新时(动画活动期间每一帧)应调用的函数。
  • onUpdateParams

    数组要传递给onUpdateonUpdategsap.timeline({onUpdate: myFunction, onUpdateParams: ["param1", "param2"]});.
  • paused

    Boolean如果true,动画将在创建后立即暂停。
  • repeat

    数字初始播放后应该重复的次数。例如,如果repeat设置为1repeat:1-1. repeat值应始终为整数。
  • repeatDelay

    数字repeatDelayrepeat设置为2repeatDelay设置为1repeatDelay:1
  • repeatRefresh(重复刷新)

    设置repeatRefresh: true导致一个重复的时间轴在每次完整迭代时(不包括yoyo效果)重新计算invalidate()所有子动画的当前值,并记录它们的起始/结束值。这对于使用动态值(相对、随机或基于函数的值)时很有用。例如,x: "random(-100, 100)"在每次重复时都会获得一个新的随机x值。duration, delay,以及staggerdorefresh(刷新)。
  • smoothChildTiming

    Boolean控制是否自动重新定位子动画(改变它们的startTimestartTimereverse()restart()smoothChildTiming设置为falsetruestartTimeleftHow to timelines work?”部分。
  • 哟哟(yoyo)

    Boolean如果true,每隔一次重复周期将以相反方向运行,使补间看起来来回切换(向前然后向后)。这对reversed属性。例如,如果设置为repeat设置为2yoyo设置为false,看起来就像:起点 - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - 终点。但如果设置为yoyo设置为true,看起来就像:起点 - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - 终点。

设置默认值

时间轴的defaults对象中的任何内容在其子动画创建时都会被继承,因此如果你发现自己反复设置相同的ease或者duration(或任何值),这可以帮助你使代码更简洁。例如:

// WITHOUT defaults (long)
var tl = gsap.timeline();
tl.to(".class1", { rotation: -270, duration: 1, ease: "elastic" })
.to(".class2", { rotation: -360, duration: 1, ease: "elastic" })
.to(".class3", { rotation: -180, duration: 1, ease: "elastic" });

//WITH defaults (shorter)
var tl = gsap.timeline({ defaults: { duration: 1, ease: "elastic" } });
tl.to(".class1", { rotation: -270 }) //child tweens will inherit the duration and from the parent timeline!
.to(".class2", { rotation: -360 })
.to(".class3", { rotation: -180 });

通过这种方式设置的任何默认值都将推送到每个子补间动画中 - 它不限于特定的属性子集。当子动画声明某个属性时,可随时轻松覆盖继承的默认值。

嵌套

可以将时间线无限层级地嵌套在时间线内。这可以让你模块化你的代码并使其更易于维护。例如,你可以将你的动画分部分构建,并像下面这样在主时间线中把它们拼接在一起:

function intro() {
var tl = gsap.timeline();
//...add animations here...
return tl;
}

function middle() {
var tl = gsap.timeline();
//...add animations here...
return tl;
}

function conclusion() {
var tl = gsap.timeline();
//...add animations here...
return tl;
}

// stitch them together in a master timeline...
var master = gsap.timeline();
master
.add(intro())
.add(middle(), "+=2") //with a gap of 2 seconds
.add(conclusion(), "-=1"); //overlap by 1 second

其他时间线特性

  • 使用其timeScale()方法来加快或减慢整个时间线的速度。你甚至可以通过Tween让它逐渐加速或减速,实现平滑效果!

  • 使用其progress()或者totalProgress()方法获取或设置时间线的进度(totalProgress() 包含了重复的部分)。例如,跳转到一半的位置,只需设置myTimeline.progress(0.5);.

  • 补间动画的time(), totalTime(), progress(),或者totalProgress()来快进或倒退时间线。你甚至可以将一个滑块控件绑定到其中一个参数上来让用户拖动时间线前进或后退。

  • 添加onComplete, onStart, onUpdate, onRepeat和/或onReverseComplete回调函数,使用构造函数的vars对象,例如var tl = gsap.timeline({onComplete: myFunction});.

  • 使用killTweensOf(target)杀掉时间线内某一特定对象的补间动画,或者使用getTweensOf() or get all the tweens and timelines in the timeline with getChildren().

  • Set the timeline to repeat any number of times or indefinitely. You can even set a delay between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse direction every other cycle.

  • Get the currentLabel() or find labels at various positions in the timeline using nextLabel()previousLabel()

Sample code:

// create the timeline that repeats 3 times
// with 1 second between each repeat and
// then call myFunction() when it completes
var tl = gsap.timeline({ repeat: 3, repeatDelay: 1, onComplete: myFunction });

// add a tween
tl.to(".class", { duration: 1, x: 200, y: 100 });

// add another tween 0.5 seconds after the end
// of the timeline (makes sequencing easy)
tl.to("#id", { duration: 0.8, opacity: 0 }, "+=0.5");

// reverse anytime
tl.reverse();

// Add a "spin" label 3-seconds into the timeline
tl.addLabel("spin", 3);

// insert a rotation tween at the "spin" label
// (you could also define the insertion point as the time instead of a label)
tl.to(".class", { duration: 2, rotation: "+=360" }, "spin");

// go to the "spin" label and play the timeline from there
tl.play("spin");

// nest another timeline inside your timeline...
var nested = gsap.timeline();
nested.to(".class2", { duration: 1, x: 200 });
tl.add(nested, "+=3"); //add nested timeline after a 3-second gap

时间线是如何工作的?

Every animation (Tween and Timeline) is placed on a parent Timeline. In a sense, they all have their own playheads (that's what its "time" refers to, or "totalTime" which is identical except that it includes repeats and repeatDelays) and when the parent's playhead moves to a new position, it updates the childrens' too (unless they're paused).

When a timeline renders at a particular time, it loops through its children and says "okay, you should render as if your playhead is at ____" and if that child is a Timeline with children, it does the same to its children, right on down the line. So the playheads generally remain synchronized.

When you unpause an animation (resume()或者play()), it essentially picks up the playhead and moves it so that its internal playhead is synchronized with wherever the parent's playhead is at that moment, thus things play perfectly smoothly. That is, unless the timeline's smoothChildTiming设置为false的情况下该子级将不会移动 - 它的startTime将锁定在它原来的位置上。

所以基本上当你调用smoothChildTiming设置为true时,引擎会动态调整内容以确保播放头对齐,使得播放过程感觉无缝且流畅。当你reverse()或更改timeScale等操作时也会发生同样的事情 - 动画的开始时间会自动偏移。但有时候你可能不希望这个行为 - 这就是为什么在父时间线上使用smoothChildTiming: false很方便的原因。

再举一个例子:假设你有一个10秒的补间动画,它位于根时间线上,而你现在正处于该补间的第2秒。我们假设它的起始位置正好是根时间线上的0秒以便简化说明,然后在它运行到第2秒时,你执行了tween.seek(5)。根时间线的播放头不会受到影响 - 它将继续按照原有的节奏运行,但为了让该补间跳转到第5秒并正确播放,该补间的startTime会被修改为-3。这种方法下,补间的播放头和根时间线的播放头就完全对齐了。

注意事项
  • 你可以通过gsap.globalTimeline访问GSAP的全局时间线,但要小心,例如,如果你暂停(pause())或者改变其时间缩放(timeScale()),这会影响包括延迟调用(delayedCalls)在内的所有内容。你可以改用gsap.exportRoot()来基本包装根时间线上现有的所有动画(可选地排除延迟调用),将它们放入一个新的时间线实例中,将这些动画与你之后创建的新动画隔离。例如,如果你在游戏中有一系列动画正在进行,用户点击按钮弹出一个模态窗口,要求将游戏动画速度降为原来的十分之一……但你想让模态窗口的动画保持全速运行,这就是 exportRoot() 的典型应用场景。

属性

autoRemoveChildren:布尔值

如果true,子补间动画和时间轴将在它们完成时立即被移除。

数据: *

可以存储任何你想要的数据的地方(初始时用vars.data如果存在的话)进行填充。

标签: 对象

这会存储已添加到时间轴的所有标签。

父级:时间轴

父级时间轴动画所依附的父级。你创建的不在任何时间轴中的内容将被放置在gsap.globalTimeline默认情况下。

scrollTrigger: ScrollTrigger| undefined

一种方便访问与时间轴关联的 ScrollTrigger 的方式。只有当时间轴具有 ScrollTrigger 时才能访问。

smoothChildTiming:布尔值

控制是否自动重新定位子补间动画和时间轴(更改它们的startTime)以保持流畅播放,当属性动态更改时。

vars: 对象

通过构造函数传递给原始时间轴的配置对象,例如gsap.timeline({onComplete: func});

方法

添加( child:[Tween | Timeline | Label | Callback | Array], position:[Number | String | Label] ):self

[覆盖] 向时间轴中添加一个补间动画、时间轴、回调或标签(或者它们的数组)。

addLabel( label:String, position:[Number | String] ):self

向时间轴添加一个标签,便于标记重要的位置/时间。

addPause( position:[String | Number | Label], callback:Function, params:Array ):self

插入一个特殊的回调,在特定时间或标签处暂停时间轴的播放。

call( callback:Function, params:Array, position:* ):self

将回调添加到时间轴的末尾(或使用position参数)——这是一种便捷方法,功能与以下内容完全相同:add( gsap.delayedCall(...) )但代码量更少。

clear( labels:Boolean ):self

清空时间轴内的所有补间动画、时间轴和回调(也可以一并清除标签)。

currentLabel( value:String ):[String | self]

获取当前时间之前或等于该时间的最近标签,或者跳转到提供的标签(行为取决于是否向方法传递参数)。

delay(value:Number):[Number | self]

获取或设置动画的初始delay即动画开始前的秒数。

持续时间(value:Number):[Number | self]

[覆盖] 获取时间轴的持续时间,或者作为设置器使用时调整时间轴的时间比例以适应指定的持续时间。

endTime( includeRepeats:Boolean ):[Number | self]

Returns the time at which the animation will finish according to the parent timeline's local time.

根据父时间线的本地时间返回动画结束的时间。(type:String, callback:Function, params:Array):[Function | self]

eventCallbackonComplete, onUpdate, onStart, onReverseComplete,或者onRepeat或或以及应传递给该回调的任何参数。

来自( 目标:[ 对象 | 数组 | 字符串 ], 变量:对象, 位置:[ 数字 | 字符串 ] ) : 自身

添加一个.from()补间动画到时间轴的末尾(或者使用position参数)——这是一种便捷方法,功能与以下内容完全相同:add( gsap.from(...) )但代码量更少。

fromTo( target:[ Object | Array | String ], fromVars:Object, toVars:Object, position:[ Number | String ] ):self

添加一个.fromTo()补间动画到时间轴的末尾——这是一个便捷方法,实现的目的与add( gsap.fromTo(...) )但代码量更少。

getById( id:String ):Animation

getChildren( nested:Boolean, tweens:Boolean, timelines:Boolean, ignoreBeforeTime:Number ):Array

返回一个包含此时间轴内嵌套的所有补间动画和/或时间轴的数组。

getTweensOf( target:[Object | Selector text | Array], nested:Boolean ):Array

返回此时间轴内某个特定对象的补间动画。

globalTime(localTime:Number):Number

将本地时间转换为对应的gsap.globalTimeline时间(考虑所有嵌套、时间缩放等)。

invalidate():self

[覆盖] 清除任何内部记录的起始/结束值,如果你想重新启动动画而不恢复到之前记录的起始值,这会很有用。

isActive( ) : Boolean

表示动画当前是否处于活动状态(意味着虚拟播放头正在此实例的时间范围内主动移动,并且未暂停,也没有其祖先时间线被暂停)。

iteration(value:Number):[Number | self]

获取或设置时间轴的迭代次数(即当前重复次数)。

kill( ):Timeline

立即销毁时间轴并将其从父时间轴中移除,停止其动画。

killTweensOf( targets:Selector text | Array | Object, props:String, onlyActive:Boolean ):Timeline

销毁此时间轴内影响所提供的targets的所有补间动画。你可以选择性地指定你想要销毁的特定属性。

nextLabel( time:Number ):String

从提供的时间点开始返回时间轴中的下一个标签。如果没有提供time,则使用时间轴当前的播放头时间。

暂停( atTime:*, suppressEvents:Boolean ):self

暂停实例,可选地跳转到特定时间。

paused(值:布尔):[布尔 | 自身]

获取或设置动画的暂停状态,该状态表示动画当前是否处于暂停状态。

play(from:*, suppressEvents:Boolean):self

开始向前播放,可选从特定时间开始(默认情况下播放从播放头当前所在的位置开始)。

previousLabel( time:Number ):String

从提供的时间点开始返回时间轴中的上一个标签。如果没有提供time中转换后的坐标。如果没有提供time,则使用时间轴当前的播放头时间。

progress(进度)(value:Number, suppressEvents:Boolean):[Number | self]

[覆盖] 获取或设置时间轴的进度,其值范围为 0 到 1,表示虚拟播放头的位置(不包括重复),其中 0 是起点,0.5 是一半完成状态,1 是完成。

recent( ):[Tween | Timeline | Callback]

返回最近添加的子补间动画/时间轴/回调,无论其在时间轴中的位置如何。

remove( value:[Tween | Timeline | Callback | Label] ):self

从时间轴中移除一个补间动画、时间轴、回调或标签(或它们的数组)。

removeLabel( label:String ):self

从时间轴中移除一个标签,并返回该标签的时间。

removePause( position:[Number | Label] ):self

移除通过其添加到时间轴的暂停。.addPause()方法快速转换任何坐标。

repeat(value:Number):[Number | self]

获取或设置时间轴在其第一次迭代后应重复的次数。

repeatDelay(value:Number):[Number | self]

获取或设置两次重复之间以秒为单位的时间长度。

restart(includeDelay:Boolean, suppressEvents:Boolean):self

重新启动并从开头开始向前播放。

resume():self

恢复播放而不改变方向(向前或向后)。

reverse(from:*, suppressEvents:Boolean):self

反向播放,使动画的所有方面都反向呈现,例如补间的缓动效果。

reversed(值:布尔):[布尔 | 自身]

获取或设置动画的反向状态,该状态表示动画是否应该反向播放。

revert():Self

撤销时间轴并将其销毁,将目标恢复到动画前的状态,包括移除时间轴添加的内联样式。

seek( position:*, suppressEvents:Boolean ):self

[覆盖] 跳转到特定时间(或标签),而不影响实例是否暂停或倒放。

设置( 目标:[ 对象 | 数组 | 字符串 ], 变量:对象, 位置:[ 数字 | 字符串 ] ) : 自身

添加一个零持续时间的补间动画到时间轴的末尾(或者使用参数指定其他位置),当虚拟播放头到达时间轴上的该位置时立即设置值 —— 这是一种便捷方法,实现的功能与以下方法完全相同:position参数)该方法在时间轴的末尾(或使用参数指定其他位置)add( gsap.to(target, {duration: 0, ...}) )但代码量更少。

移动子项( 数量:数字, 调整标签:Boolean, 忽略之前时间:数字 ) : 自身

按一定数量移动时间轴子项的开始时间,并可选地调整标签。

startTime(value:Number):[Number | self]

获取或设置动画在其父时间线上的开始时间(定义的延迟之后)。

then(callback:Function):Promise

返回一个Promise,以便您可以使用Promise跟踪补间或时间线何时完成。

time(value:Number, suppressEvents:Boolean):[Number | self]

[覆盖] 获取或设置播放头的本地位置(本质上是当前时间),不包括任何重复或重复延迟。

timeScale(value:Number):[Number | self]

用于在动画中缩放时间的因子,其中1 = 正常速度(默认值),0.5 = 半速,2 = 双倍速度,依此类推。

设置为( 目标:[ 对象 | 数组 | 字符串 ], 变量:对象, 位置:[ 数字 | 字符串 ] ) : 自身

添加一个gsap.to()补间动画到时间轴的末尾(或者使用position参数)——这是一种便捷方法,功能与以下内容完全相同:add( gsap.to(...) )但代码量更少。

totalDuration(value:Number):[Number | self]

获取或设置时间轴的总持续时间(包括任何重复和重复延迟)以秒为单位。

totalProgress(value:Number, suppressEvents:Boolean):[Number | self]

[覆盖] 获取或设置时间轴的总体进度,其值介于0到1之间,表示虚拟播放头的位置(包括重复),0表示开始,0.5表示一半进度,1表示结束(完成)。

totalTime(time:Number, suppressEvents:Boolean):[Number | self]

根据播放头的位置进行获取或设置,这totalDuration其中包含任何重复和重复延迟。

从某一状态补间到另一状态( 起始位置:[数字 | 标签], 结束位置:[数字 | 标签], 变量:对象 ) : 补间动画

创建一个线性补间动画,将播放头从某个特定时间或标签逐渐移动到另一个时间或标签,然后停止。

补间到指定位置( 位置:[数字 | 标签], 变量:对象 ) : 补间动画

创建一个线性补间动画,将播放头逐步移动到特定时间或标签,然后停止。

哟哟(yoyo)(值:布尔):[布尔 | 自身]

获取或设置时间轴的往返状态,true 会使时间轴来回播放,在每次重复时交替向前和向后。

无噪 Logo
无噪文档
中文文档 · 复刻官网
查看所有 ↗