我正在構建一個使用 Web Animations API 的影片工具,我遇到的問題是每次播放影片時,我實際上是在創建一個新影片,所以如果我執行 console.log(el.getAnimations())它將回傳一個包含多個影片的陣列,但我只使用了最后一個,這當然會浪費大量記憶體。如何重用或洗掉第一個影片?
要為元素設定影片,我這樣做:
function play(){
el?.animate(el.kfs, {
duration: duration.value,
delay: -currentTime.value,
iterations: Infinity,
composite: "replace",
})
}
并暫停我這樣做的影片:
function pause(){
el?.getAnimations().forEach(anim => anim?.pause()
}
這是一個簡單的作業示例:
const el = document.getElementById('el')
function playAnim(){
el.animate(
[{backgroundColor:'red'}, {backgroundColor:'black'}],
{
duration: 1000,
iterations: Infinity
})
}
playAnim()
el.getAnimations()[0].pause()
playAnim()
console.log(el.getAnimations().length) // will output 2
<div id="el">el</div>
uj5u.com熱心網友回復:
聽起來你不愿意“暫停”影片而是“取消”它。為此,請使用該cancel()方法。
const el = document.getElementById('el')
function playAnim(){
el.animate(
[{backgroundColor:'red'}, {backgroundColor:'black'}],
{
duration: 1000,
iterations: Infinity
})
}
playAnim()
el.getAnimations()[0].cancel()
playAnim()
console.log(el.getAnimations().length) // will output 2
<div id="el">el</div>
uj5u.com熱心網友回復:
const el = document.getElementById('el');
const kfs = [{backgroundColor:'red'}, {backgroundColor:'black'}];
function playAnim(){
let anim = el.getAnimations()[0];
if(anim){
let eff = anim.effect;
eff.setKeyframes(kfs);
anim.play();
}else{
el.animate(kfs,
{
duration: 1000,
iterations: Infinity
});
}
}
playAnim()
el.getAnimations()[0].pause()
playAnim()
console.log(el.getAnimations().length)
<div id="el">el</div>
我已經解決了,方法是獲取影片,然后獲取影片的keyframeEffect,并使用setKeyframes方法,然后播放影片。
正如 Kaiido 所說,如果我們想洗掉影片而不是替換它,那么使用 anim.cancel() 就可以了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535490.html
上一篇:從陣列影片中選擇隨機顏色,重復,從陣列中選擇一個新的隨機顏色?
下一篇:在影片情節中圍繞點繪制圓圈
