?
This document uses PHP Chinese website manual Release
概述
cancelAnimationFrame方法
實例
參考鏈接
requestAnimationFrame是瀏覽器用于定時循環(huán)操作的一個接口,類似于setTimeout,主要用途是按幀對網(wǎng)頁進(jìn)行重繪。
設(shè)置這個API的目的是為了讓各種網(wǎng)頁動畫效果(DOM動畫、Canvas動畫、SVG動畫、WebGL動畫)能夠有一個統(tǒng)一的刷新機(jī)制,從而節(jié)省系統(tǒng)資源,提高系統(tǒng)性能,改善視覺效果。代碼中使用這個API,就是告訴瀏覽器希望執(zhí)行一個動畫,讓瀏覽器在下一個動畫幀安排一次網(wǎng)頁重繪。
requestAnimationFrame的優(yōu)勢,在于充分利用顯示器的刷新機(jī)制,比較節(jié)省系統(tǒng)資源。顯示器有固定的刷新頻率(60Hz或75Hz),也就是說,每秒最多只能重繪60次或75次,requestAnimationFrame的基本思想就是與這個刷新頻率保持同步,利用這個刷新頻率進(jìn)行頁面重繪。此外,使用這個API,一旦頁面不處于瀏覽器的當(dāng)前標(biāo)簽,就會自動停止刷新。這就節(jié)省了CPU、GPU和電力。
不過有一點(diǎn)需要注意,requestAnimationFrame是在主線程上完成。這意味著,如果主線程非常繁忙,requestAnimationFrame的動畫效果會大打折扣。
requestAnimationFrame使用一個回調(diào)函數(shù)作為參數(shù)。這個回調(diào)函數(shù)會在瀏覽器重繪之前調(diào)用。
requestID = window.requestAnimationFrame(callback);
目前,主要瀏覽器Firefox 23 / IE 10 / Chrome / Safari)都支持這個方法??梢杂孟旅娴姆椒?,檢查瀏覽器是否支持這個API。如果不支持,則自行模擬部署該方法。
window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();
上面的代碼按照1秒鐘60次(大約每16.7毫秒一次),來模擬requestAnimationFrame。
使用requestAnimationFrame的時候,只需反復(fù)調(diào)用它即可。
function repeatOften() { // Do whatever requestAnimationFrame(repeatOften); } requestAnimationFrame(repeatOften);
cancelAnimationFrame方法用于取消重繪。
window.cancelAnimationFrame(requestID);
它的參數(shù)是requestAnimationFrame返回的一個代表任務(wù)ID的整數(shù)值。
var globalID; function repeatOften() { $("<div />").appendTo("body"); globalID = requestAnimationFrame(repeatOften); } $("#start").on("click", function() { globalID = requestAnimationFrame(repeatOften); }); $("#stop").on("click", function() { cancelAnimationFrame(globalID); });
上面代碼持續(xù)在body元素下添加div元素,直到用戶點(diǎn)擊stop按鈕為止。
下面,舉一個實例。
假定網(wǎng)頁中有一個動畫區(qū)塊。
<div id="anim">點(diǎn)擊運(yùn)行動畫</div>
然后,定義動畫效果。
var elem = document.getElementById("anim"); var startTime = undefined; function render(time) { if (time === undefined) time = Date.now(); if (startTime === undefined) startTime = time; elem.style.left = ((time - startTime)/10 % 500) + "px"; }
最后,定義click事件。
elem.onclick = function() { (function animloop(){ render(); requestAnimFrame(animloop); })(); };
運(yùn)行效果可查看jsfiddle。
Paul Irish, requestAnimationFrame for smart animating
Chris Coyier, Using requestAnimationFrame