window.requestAnimationFrame/cancelAnimationFrame使用
阿新 • • 發佈:2021-01-15
技術標籤:javascript
window.requestAnimationFrame(callback)/ cancelAnimationFrame(callback)
window. requestAnimationFrame(callback)建立一個自定義執行動畫,
cancelAnimationFrame(callback)取消該自定義動畫
callback需要穿進去的回撥函式(自定義),
與window.setInterval定時器類似,又不相同。在更新動畫時,相比setInterval定時器,更推薦使用requestAnimationFrame。
官方文件釋義:window.requestAnimationFrame() 告訴瀏覽器——你希望執行一個動畫,並且要求瀏覽器在下次重繪之前呼叫指定的回撥函式更新動畫。該方法需要傳入一個回撥函式作為引數,該回調函式會在瀏覽器下一次重繪之前執行。
☆注意:若你想在瀏覽器下次重繪之前繼續更新下一幀動畫,那麼回撥函式自身必須再次呼叫window.requestAnimationFrame()。
let targetBox = window.document.getElementById("target-box");
let container = window.document.getElementById("container");
let left = parseInt(getComputedStyle(targetBox).left);
let counter=0;
let tempLeft=left;
var start = null;
function interval(timestamp){
if (!start) start = timestamp;
var progress = timestamp - start;
counter++;
left+=10;
console.log(counter);
targetBox.style.left=`${left}px`;
if(counter>100){
counter=0;
left = tempLeft;
}
if (progress < 20000) {
window.requestAnimationFrame(interval);
}
}
window.requestAnimationFrame(interval);
<div class="target-box" id="target-box"></div>
<div class="container" id="container"></div>
.body {
position: relative;
}
.container {
width: 200px;
height: 300px;
background: rgba(66, 41, 11, 0.239);
}
.target-box {
position: absolute;
top: 300px;
left: 300px;
width: 30px;
height: 30px;
background: aquamarine;
}
如前面所說,需要在回撥函式體內再次呼叫
window.requestAnimationFrame(callback);
let counter = 0;
let start = null;
function animation(timestamp){
if(!start) start = timestamp;
let progress = timestamp - start;
counter ++;
if(progress < 20000)
window.requestAnimationFrame(animation);
console.log(counter);
}
window.requestAnimationFrame(animation);
當我們想在某個計數器節點取消動畫執行,使用cancelAnimationFram(callback);即可
let counter = 0;
let start = null;
function animation(timestamp){
if(!start) start = timestamp;
let progress = timestamp - start;
counter ++;
if(counter>9){
window.cancelAnimationFrame(animation);
}else{
if(progress < 20000)
window.requestAnimationFrame(animation);
}
console.log(counter);
}
window.requestAnimationFrame(animation);