我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

分析JavaScript中CSS关键帧的强大功能

本篇内容介绍了“分析JavaScript中CSS关键帧的强大功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

创新互联是一家集网站建设,鸡西企业网站建设,鸡西品牌网站建设,网站定制,鸡西网站建设报价,网络营销,网络优化,鸡西网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

创建一个简单的关键帧Web Animation

要使用Web Animation API为关键帧动画设置动画,只需animate()在元素上调用该函数:

1

"vertical-align: inherit;">"vertical-align: inherit;">Element.animate(关键帧,关键帧选项)

该函数接受两个参数:

  • keyframes:包含所需CSS关键帧的JavaScript表示的文字数组

  • keyframeOptions:包含动画的其他设置的文字,例如缓动,持续时间,填充模式等。

看一下下面的简单示例,该示例使用 animate()函数而不是CSS关键帧来渲染动画:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

"vertical-align: inherit;">"vertical-align: inherit;">var boxframes = ["vertical-align: inherit;">"vertical-align: inherit;">

    {"vertical-align: inherit;">"vertical-align: inherit;">

        变换:'translateX(0)'

        background: 'red',

        borderRadius: 0

    },

    {

        transform: 'translateX(200px) scale(.5)',

        background: 'orange',

        borderRadius: 0,

        offset: 0.6 /* set explicit point (60%) when frame starts */

    },

    {

        transform: 'translateX(400px)',

        background: 'green',

        borderRadius: '50%'

    }

]

如果我们使用纯CSS声明上面的内容,它看起来像这样:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@keyframes animatethebox{

    0%{

        transform: translateX(0);

        background: red;

        borderRadius: 0;

    }

    

    60%{

        transform: translateX(200px) scale(.5);

        background: orange;

        borderRadius: 0;

    }

    

    100%{

        transform: translateX(400px);

        background: green;

        borderRadius: 50%;

    }

}

正如您所看到的,这两种语法非常相似,如果您已经熟悉CSS关键帧,那么将它移植到JavaScript就没有问题。与JavaScript版本的一些区别值得记住:

  • 在JavaScript版本中,属性字符串值应该在引号(transform: 'translateX(0)')中

  • 带连字符的属性名称必须转换为camelCase而不是(borderRadius: 0)。

  • 逗号而不是分号应该跟踪每个属性声明(最后一个属性除外)

默认情况下,使用JavaScript设置的关键帧在播放时均匀分布,每个关键帧的时间相同。但是,通过offset在关键帧中添加属性,我们可以设置该关键帧应该开始播放的点,例如60%标记的0.6,类似于使用纯CSS的关键帧。

keyframeOptions参数

animate()方法的第二个参数是一个文字,可以很好地调整动画的行为。许多选项直接从CSS的animation-*属性映射,例如“ animation-delay”,“ animation-fill-mode”等。所有属性都是可选的,如果没有设置,则回退到默认值:

 
propertyCSS Property EquivalentDescription
idnoneOption that sets the name of this Animation to refer back to later in your code.
delayanimation-delayThe delay (integer) before the animation starts in milliseconds. Defaults to 0s.
directionanimation-directionDefines whether the animation should play as normal, in reverse, or alternate between the two. Possible values are:
  • normal: The animation plays forward as normal. After each animation cycle, the animation resets to the beginning state and starts over again. Default value.

  • reverse: Plays the animation in reverse, starting from the end state.  After each animation cycle, the animation resets to the end state and starts over again.

  • alternate: The animation alternates between normal and reverse directions. In reverse, the animation starts at the end state and plays backwards. The animation timing function is also reversed.

  • alternate-reverse: The animation alternates between reverse and normal directions, starting in reverse for the first iteration.

durationanimation-delayThe duration (integer) of the animation in milliseconds, such as 1000. Default to 0 (no animation, jumps to last frame).
easinganimation-timing-functionSets the easing function used to animate the @keyframe animation. Valid values include "ease", "ease-in", "ease-in-out","linear", "frames(integer)" etc. Defaults to "linear".
endDelayn/aThe number of milliseconds to delay after the end of an animation. This is useful when sequencing multiple animations based on the end time of another animation. Defaults to 0.
fillanimation-fill-modeDefines how the animation should apply styles to its target when the animation isn't playing anymore. Defaults to "none". Possible values are:
  • none: The animation should not apply any styles to the target when it is not playing. Default value.

  • forwards: The target element will retain the computed styles defined in the last key frame (ie: when key frame is at 100%) when the animation isn't playing.

  • backwards: The target element will retain the computed styles defined in the first key frame (ie: when key frame is at 0%) when the animation isn't playing.

  • both: The target element will retain the computed styles defined in both the first and last key frames when the animation isn't playing.

iterationStartn/aSets the point in the iteration the animation should start. The value should be a positive, floating point number. In an animation with 1 iteration, a iterationStart value of 0.5 starts the animation half way through. In an animation with 2 iterations, a iiterationStart value of 1.5 starts the animation half way through the 2nd iteration etc. Defaults to 0.0.
iterations

 

 

animation-iteration-countSets the number of times the animation should run before stopping. A value of Infinity means forever. Defaults to 1.

这是我在上面的例子中使用的keyframeOptions参数:

1

2

3

4

5

6

var boxref = document.getElementById("box")

boxref.animate(boxframes, {

    duration: 1000,

    fill: 'forwards',

    easing: 'ease-in'

})

如果我们想使用动画速记属性在CSS中定义相同的选项,它将如下所示:

1

animation: animatethebox 1s ease-in forwards;

控制动画(播放,暂停等)

使用Animation API创建关键帧动画的部分优点是可以按需操作结果,例如暂停,跳过或挂钩到动画的事件处理程序。执行所有这些操作的第一步是在调用animate()方法时将动画分配给变量:

var myanimation = Element.animate(keyframes, keyframeOptions)

这将创建对Animation对象实例的引用,以允许我们通过各种公开的属性和方法来操作动画:

1

2

3

4

var myanimation = Element.animate(/* .. */)

myanimation.pause() // immediately pause animation to control it manually

myanimation.curentTime = 1000 // jump to 1 second from start of animation

myanimation.play() // play animation

这是修改后使用控件进行回放的原始示例:

请注意,在此示例中,我animate()立即调用目标元素,这将导致动画立即运行。为了防止这种情况,我pause()随后调用了该 方法。这是您希望手动控制动画时使用的常用模式:

1

2

3

4

5

6

7

var boxanimation = boxref.animate(boxframes, {

    duration: 1000,

    fill: 'both',

    easing: 'ease-in'

})

boxanimation.pause()

动画对象实例属性和方法

下面列出了动画对象实例的属性,方法和事件处理程序,如上所述,在为animate()方法分配引用时创建:

属性

  • currentTime: Gets or sets the current time value of the animation in milliseconds.

  • effect:  Gets or sets the target effect of an animation. Support for this property is currently limited in all browsers.

  • finished: A promise object that's resolved when the animation has completed. Support for this property is currently limited in all browsers.

  • id: Gets or sets a string used to identify the animation.

  • playbackRate: Integer that gets or sets a playback rate of the animation. For example, 1=normal, 0 = pause, 2 = double, -1 = backwards etc.

  • playState: Read-only property that returns the current state of the animation: "idle", "pending", "running", "paused", or "finished".

  • ready: A promise object that's resolved when the animation is ready to be played. Support for this property is currently limited in all browsers.

  • startTime: Floating point number that gets or sets the current time (in milliseconds) of the animation.

  • timeline: Gets or sets the current timeline of the animation. Defaults to the document timeline (document.timeline). Support for this property is currently limited in all browsers.

方法

  • cancel(): Cancels the animation.

  • finish(): Immediately completes an animation.

  • pause(): Pauses an animation.

  • play(): Plays an animation.

  • reverse(): Reverses the current direction of the animation and plays it.

事件处理程序

  • oncancel: Triggered when the animation is canceled, such as by calling the cancel() method.

  • onfinish: Triggered when the animation is finished, such as by calling the finish() method.

使用Web Animation API创建简单的scrubber

通过操作currentTime属性,下面为我们看到的基本动画添加了一个简单的擦除器:

我创建了一个HTML5 Range Slider来用作scrubber。当动画首次运行(自动)时,动画的currentTime 属性值将持续传送到滑块,以使两者同步。目前没有“onprogress”事件处理程序或类似的东西(据我所知)只在WAAPI动画运行时运行代码,所以我用它 来监视动画的进度。动画结束后,我利用WAAPI事件调用并不必要地停止更新滑块。  requestAnimationFrame()onfinishcancelAnimationFrame()

每当用户与Ranger Slider交互时,我都会更新WAAPI动画以与滑块同步:

1

2

3

4

5

6

7

8

9

10

11

12

scrubber.addEventListener('mousedown', ()=>{

    boxanimation.pause()

    updateScrubber()

})

scrubber.addEventListener('mouseup', ()=>{

    boxanimation.play()

})

scrubber.addEventListener('input', ()=>{

    boxanimation.currentTime = scrubber.value * animationlength

})

当用户按下滑块时,我暂停动画并更新滑块的值以与动画的currentTime 属性同步。当用户拖动滑块时,反过来发生 - 我同步currentTime属性以反映滑块的值,因此前者依赖于后者。最后,当用户将鼠标放在滑块上时,我恢复动画的自动播放。

一次动画多个元素

在下一个示例中,我将使用WAAPI一次演示动画多个元素,并在它们全部结束后执行动作。

注意:在撰写本文时,即使在Chrome和FF中,对WAAPI 承诺的原生支持也很不稳定 。我不得不使用 Web Animation Next Polyfill来使这个功能在浏览器中运行。

这里没有什么太复杂的事了。基本上我循环并调用animate() 标题中的每个字母,并将每个Animation对象实例存储在数组中。有了这个数组,我可以根据需要循环播放一系列动画。每个动画的finished属性都返回一个 Promise,该动画在动画完成播放时被解析,我利用 Promise.all()在所有动画完成播放时重置整个动画。

使用Animation()构造函数创建动画

到目前为止,我只使用animate()对象直接在一个元素上创建了WAAPI动画,该元素返回一个Animation对象实例。我会失职但更不用说你也可以使用Animation() 构造函数来完成同样的事情。

注意:Animation()在撰写本文时,即使在Chrome和FF中,本机支持也是不稳定的。我不得不使用 Web Animation Next Polyfill来使这个功能在浏览器中运行。

有了警告,这里是如何调用 Animation() 构造函数:

1

var myanimation = new Animation([effect][, timeline]);

该函数接受两个参数:

  • effect:动画效果。在撰写本文时,仅keyframeEffect支持该对象。

  • timeline:动画时间轴。在撰写本文时,仅document.timeline支持。

让我们看一下如何使用一个简单的例子:

这是JavaScript代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

var boxref = document.getElementById("box")

var boxkeyFrames = new KeyframeEffect(

    boxref, // element to animate

    [

        { transform: 'translateX(0) rotate(0deg)', background:'red' }, // keyframe

        { transform: 'translateX(90vw) rotate(180deg)', background:'blue' }

    ],

        { duration: 2000, fill: 'forwards', iterations: 5 } // keyframe options

);

var boxanimation = new Animation(boxkeyFrames, document.timeline)

boxanimation.play()

KeyframeEffect()对象是一个一体化对象,它包含一个位置的动画的所有设置,从目标元素,要使用的关键帧到关键帧选项。

“分析JavaScript中CSS关键帧的强大功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


网站题目:分析JavaScript中CSS关键帧的强大功能
标题路径:http://shouzuofang.com/article/gicpjg.html

其他资讯