溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

分析JavaScript中CSS關(guān)鍵幀的強大功能

發(fā)布時間:2021-11-06 14:22:16 來源:億速云 閱讀:106 作者:iii 欄目:web開發(fā)

本篇內(nèi)容介紹了“分析JavaScript中CSS關(guān)鍵幀的強大功能”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

創(chuàng)建一個簡單的關(guān)鍵幀Web Animation

要使用Web Animation API為關(guān)鍵幀動畫設(shè)置動畫,只需animate()在元素上調(diào)用該函數(shù):

1

<font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Element.animate(關(guān)鍵幀,關(guān)鍵幀選項)</font></font>

該函數(shù)接受兩個參數(shù):

  • keyframes:包含所需CSS關(guān)鍵幀的JavaScript表示的文字?jǐn)?shù)組

  • keyframeOptions:包含動畫的其他設(shè)置的文字,例如緩動,持續(xù)時間,填充模式等。

看一下下面的簡單示例,該示例使用 animate()函數(shù)而不是CSS關(guān)鍵幀來渲染動畫:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<font style="vertical-align: inherit;"><font style="vertical-align: inherit;">var boxframes = [</font></font><font></font><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">

    {</font></font><font></font><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">

        變換:'translateX(0)',</font></font><font></font>

        background: 'red',<font></font>

        borderRadius: 0<font></font>

    },<font></font>

    {<font></font>

        transform: 'translateX(200px) scale(.5)', <font></font>

        background: 'orange',<font></font>

        borderRadius: 0,<font></font>

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

    },<font></font>

    {<font></font>

        transform: 'translateX(400px)',<font></font>

        background: 'green',<font></font>

        borderRadius: '50%'<font></font>

    }<font></font>

]

如果我們使用純CSS聲明上面的內(nèi)容,它看起來像這樣:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@keyframes animatethebox{<font></font>

    0%{<font></font>

        transform: translateX(0);<font></font>

        background: red;<font></font>

        borderRadius: 0;<font></font>

    }<font></font>

    <font></font>

    60%{<font></font>

        transform: translateX(200px) scale(.5);<font></font>

        background: orange;<font></font>

        borderRadius: 0;<font></font>

    }<font></font>

    <font></font>

    100%{<font></font>

        transform: translateX(400px);<font></font>

        background: green;<font></font>

        borderRadius: 50%;<font></font>

    }<font></font>

}

正如您所看到的,這兩種語法非常相似,如果您已經(jīng)熟悉CSS關(guān)鍵幀,那么將它移植到JavaScript就沒有問題。與JavaScript版本的一些區(qū)別值得記?。?/p>

  • 在JavaScript版本中,屬性字符串值應(yīng)該在引號(transform: 'translateX(0)')中

  • 帶連字符的屬性名稱必須轉(zhuǎn)換為camelCase而不是(borderRadius: 0)。

  • 逗號而不是分號應(yīng)該跟蹤每個屬性聲明(最后一個屬性除外)

默認(rèn)情況下,使用JavaScript設(shè)置的關(guān)鍵幀在播放時均勻分布,每個關(guān)鍵幀的時間相同。但是,通過offset在關(guān)鍵幀中添加屬性,我們可以設(shè)置該關(guān)鍵幀應(yīng)該開始播放的點,例如60%標(biāo)記的0.6,類似于使用純CSS的關(guān)鍵幀。

keyframeOptions參數(shù)

animate()方法的第二個參數(shù)是一個文字,可以很好地調(diào)整動畫的行為。許多選項直接從CSS的animation-*屬性映射,例如“ animation-delay”,“ animation-fill-mode”等。所有屬性都是可選的,如果沒有設(shè)置,則回退到默認(rèn)值:

 
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參數(shù):

1

2

3

4

5

6

var boxref = document.getElementById("box")<font></font>

boxref.animate(boxframes, {<font></font>

    duration: 1000,<font></font>

    fill: 'forwards',<font></font>

    easing: 'ease-in'<font></font>

})

如果我們想使用動畫速記屬性在CSS中定義相同的選項,它將如下所示:

1

animation: animatethebox 1s ease-in forwards;

控制動畫(播放,暫停等)

使用Animation API創(chuàng)建關(guān)鍵幀動畫的部分優(yōu)點是可以按需操作結(jié)果,例如暫停,跳過或掛鉤到動畫的事件處理程序。執(zhí)行所有這些操作的第一步是在調(diào)用animate()方法時將動畫分配給變量:

var myanimation = Element.animate(keyframes, keyframeOptions)

這將創(chuàng)建對Animation對象實例的引用,以允許我們通過各種公開的屬性和方法來操作動畫:

1

2

3

4

var myanimation = Element.animate(/* .. */)<font></font>

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

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

myanimation.play() // play animation

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

請注意,在此示例中,我animate()立即調(diào)用目標(biāo)元素,這將導(dǎo)致動畫立即運行。為了防止這種情況,我pause()隨后調(diào)用了該 方法。這是您希望手動控制動畫時使用的常用模式:

1

2

3

4

5

6

7

var boxanimation = boxref.animate(boxframes, {<font></font>

    duration: 1000,<font></font>

    fill: 'both',<font></font>

    easing: 'ease-in'<font></font>

})<font></font>

<font></font>

boxanimation.pause()

動畫對象實例屬性和方法

下面列出了動畫對象實例的屬性,方法和事件處理程序,如上所述,在為animate()方法分配引用時創(chuàng)建:

屬性

  • 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創(chuàng)建簡單的scrubber

通過操作currentTime屬性,下面為我們看到的基本動畫添加了一個簡單的擦除器:

我創(chuàng)建了一個HTML5 Range Slider來用作scrubber。當(dāng)動畫首次運行(自動)時,動畫的currentTime 屬性值將持續(xù)傳送到滑塊,以使兩者同步。目前沒有“onprogress”事件處理程序或類似的東西(據(jù)我所知)只在WAAPI動畫運行時運行代碼,所以我用它 來監(jiān)視動畫的進度。動畫結(jié)束后,我利用WAAPI事件調(diào)用并不必要地停止更新滑塊。  requestAnimationFrame()onfinishcancelAnimationFrame()

每當(dāng)用戶與Ranger Slider交互時,我都會更新WAAPI動畫以與滑塊同步:

1

2

3

4

5

6

7

8

9

10

11

12

scrubber.addEventListener('mousedown', ()=>{<font></font>

    boxanimation.pause()<font></font>

    updateScrubber()<font></font>

})<font></font>

<font></font>

scrubber.addEventListener('mouseup', ()=>{<font></font>

    boxanimation.play()<font></font>

})<font></font>

<font></font>

scrubber.addEventListener('input', ()=>{<font></font>

    boxanimation.currentTime = scrubber.value * animationlength<font></font>

})

當(dāng)用戶按下滑塊時,我暫停動畫并更新滑塊的值以與動畫的currentTime 屬性同步。當(dāng)用戶拖動滑塊時,反過來發(fā)生 - 我同步currentTime屬性以反映滑塊的值,因此前者依賴于后者。最后,當(dāng)用戶將鼠標(biāo)放在滑塊上時,我恢復(fù)動畫的自動播放。

一次動畫多個元素

在下一個示例中,我將使用WAAPI一次演示動畫多個元素,并在它們?nèi)拷Y(jié)束后執(zhí)行動作。

注意:在撰寫本文時,即使在Chrome和FF中,對WAAPI 承諾的原生支持也很不穩(wěn)定 。我不得不使用 Web Animation Next Polyfill來使這個功能在瀏覽器中運行。

這里沒有什么太復(fù)雜的事了?;旧衔已h(huán)并調(diào)用animate() 標(biāo)題中的每個字母,并將每個Animation對象實例存儲在數(shù)組中。有了這個數(shù)組,我可以根據(jù)需要循環(huán)播放一系列動畫。每個動畫的finished屬性都返回一個 Promise,該動畫在動畫完成播放時被解析,我利用 Promise.all()在所有動畫完成播放時重置整個動畫。

使用Animation()構(gòu)造函數(shù)創(chuàng)建動畫

到目前為止,我只使用animate()對象直接在一個元素上創(chuàng)建了WAAPI動畫,該元素返回一個Animation對象實例。我會失職但更不用說你也可以使用Animation() 構(gòu)造函數(shù)來完成同樣的事情。

注意:Animation()在撰寫本文時,即使在Chrome和FF中,本機支持也是不穩(wěn)定的。我不得不使用 Web Animation Next Polyfill來使這個功能在瀏覽器中運行。

有了警告,這里是如何調(diào)用 Animation() 構(gòu)造函數(shù):

1

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

該函數(shù)接受兩個參數(shù):

  • 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")<font></font>

<font></font>

var boxkeyFrames = new KeyframeEffect( <font></font>

    boxref, // element to animate<font></font>

    [<font></font>

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

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

    ], <font></font>

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

);<font></font>

<font></font>

var boxanimation = new Animation(boxkeyFrames, document.timeline)<font></font>

<font></font>

boxanimation.play()

KeyframeEffect()對象是一個一體化對象,它包含一個位置的動畫的所有設(shè)置,從目標(biāo)元素,要使用的關(guān)鍵幀到關(guān)鍵幀選項。

“分析JavaScript中CSS關(guān)鍵幀的強大功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI