Up to date polyfill for requestAnimationFrame

后端 未结 5 906
北恋
北恋 2021-01-12 02:51

http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision tells me that recently (Chrome 20) requestAnimationFrame has gained a new

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-12 03:43

    this might work. modified this gist

    https://gist.github.com/1579671

    (function() {
        var lastTime = 0;
        var startTime = Date().getTime();
        var vendors = ['ms', 'moz', 'webkit', 'o'];
        for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
            window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] 
                                       || window[vendors[x]+'CancelRequestAnimationFrame'];
        }
    
        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function(callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function() { callback(currTime - startTime); }, 
                  timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };
    
        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function(id) {
                clearTimeout(id);
            };
    }());
    

    get the timestamp when the closure first executes (page load), then pass into the callback the difference between the current timestamp and the original. Should give you an integer equivalent of the new method. Not as precise, but better than a totally different value.

提交回复
热议问题