Javascript:如何获取window.requestAnimationFrame之间的时差

Javascript: How to get the time difference between window.requestAnimationFrame

获取 javascript 中 "window.requestAnimationFrame" 回调之间的时间差的最佳方法是什么?

我试过:

// create the best .requestAnimationFrame callback for each browser
window.FPS = (function() {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
    function(callback) {window.setTimeout(callback, 1000 / 60);};
})();

// start animation loop
var dt, stamp = (new Date()).getTime();
function loop() {
    window.FPS(loop);
    var now = (new Date()).getTime();
    var dt = now - stamp;
    stamp = now;
}
// has "dt" the best accuracy?

has "dt" the best accuracy?

没有。根据the docs,

The callback method is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame begin to fire

所以你应该使用它来获得高精度。

function loop(now) {
    var last = now || Date.now(); // fallback if no precise time is given
    window.FPS(function(now) {
        now = now || Date.now();
        var dt = now - last;
        if (dt != 0) // something might be wrong with our frames
             console.log(dt);
        loop(now);
    });
}
window.FPS(loop);

(jsfiddle demo)

大多数现代浏览器会自动将高精度时间戳作为参数发送到每个 requestAnimation 回调循环中:http://caniuse.com/#search=performance

因此,您只需从当前时间戳中减去最后一个时间戳即可得到自上次循环以来经过的时间 运行。

这是示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var startingTime;
var lastTime;
var totalElapsedTime;
var elapsedSinceLastLoop;

var $total=$('#total');
var $loop=$('#loop');

requestAnimationFrame(loop);

function loop(currentTime){
  if(!startingTime){startingTime=currentTime;}
  if(!lastTime){lastTime=currentTime;}
  totalElapsedTime=(currentTime-startingTime);
  elapsedSinceLastLoop=(currentTime-lastTime);
  lastTime=currentTime;
  $total.text('Since start: '+totalElapsedTime+' ms');
  $loop.text('Since last loop: '+elapsedSinceLastLoop+' ms');
  requestAnimationFrame(loop);
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id=total>T1</p>
<p id=loop>T2</p>
<canvas id="canvas" width=300 height=300></canvas>

对于一些不支持 Performance 的浏览器,您必须在循环内使用 Date.now() 而不是 currentTime,因为这些浏览器不会自动发送时间戳进入循环。

我会写一个明确的结论,给大家想用这个模式

// CREATING AN FPS ENGINE

window.FPS = (function() {
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {window.setTimeout(callback, 1000 / 60);};
})();

var FPS = {
    loop: function(canvas_object) { // OPTIONAL canvas_object, I think it increases performance | canvas_object = document.getElementById("canvas_id")
        var ticks = window.FPS(function(now){
            var dt = now - FPS.stamp || 0;
            FPS.stamp = now;
            FPS.update(dt, FPS.stamp, ticks);
            FPS.loop(canvas_object);
        }, canvas_object);

    },
    update: undefined,
    stamp: undefined
};

// USING THE FPS ENGINE

FPS.loop(the_canvas_object); // starts the engine
FPS.update = function(dt, stamp, ticks) {
    // The game/video loop, using accurate dt. Stamp is the time since engine started. Ticks is the number of the loop cycles
    console.log("dt: " + dt + ", Stamp: " + stamp + ", Ticks: " + ticks); // check output   
    // HAPPY GAME CREATING
    var fps= (1 / (dt / 1000)).toFixed(1);
};