如何在不同浏览器上的requestAnimationFrame中解决不同的FPS?

Der*_*會功夫 9 javascript firefox google-chrome canvas three.js

如何requestAnimationFrame在不同的浏览器上解决不同的FPS ?
我正在使用THREE.js这种用途制作3D游戏requestAnimationFrame,它在Google Chrome 15上很快.
但是,它在Firefox 6上确实很慢,而且在IE9上确实非常慢(比Firefox慢).
这真的是一个问题,我想知道是否有解决方案.

谢谢.

Mir*_*rko 14

常见的做法是创建deltaTime(dt)变量,然后将其用作每个动画/更新周期的参数.

代码仅用于可视化问题/解决方案.

// ...
timer: function(){
    var now = new Date().getTime(); // get current time
    this.controls.dt = now - this.controls.time; // calculate time since last call
    this.controls.time = now; // update the current application time
    this.controls.frame++; // also we have a new frame
    return this.controls.dt ;
}
Run Code Online (Sandbox Code Playgroud)

对于渲染函数的任何调用,然后传递dt

// we call the update function with every request frame
update: function(){
    var dt = this.timer();
    _.each(this.activeViews, function(item){ item.update(dt); });  // this is underscore.js syntax
}
Run Code Online (Sandbox Code Playgroud)

item.update(dt)看起来像那样

//...
var x = this.position.get(x);
x = x + (10*dt); // meaning: x increases 10 units every ms.
this.position.x = x;
Run Code Online (Sandbox Code Playgroud)


ade*_*neo 5

据我所知,没有办法真正解决这个问题,除了使你的代码减少资源密集.

Chrome似乎是最快的浏览器,但通常FF也不甘落后,但IE仍然很慢.取决于渲染方法,canvas,svg或webGL,它也非常依赖于本地硬件,因为它在大多数情况下使用客户端,而复杂的webGL渲染需要强大的GPU来实现良好的帧速率.

有一些方法可以动态测量帧速率,并相应地更改动画.
这是一个测量帧率的非常简单的例子.

function step(timestamp) {
    var time2 = new Date;
    var fps   = 1000 / (time2 - time);
    time = time2;
	
    document.getElementById('test').innerHTML = fps;
    window.requestAnimationFrame(step);
}

var time = new Date(), i = 0;
window.requestAnimationFrame(step);
Run Code Online (Sandbox Code Playgroud)
<div id="test"></div>
Run Code Online (Sandbox Code Playgroud)

这只是一个不那么准确的即时测量,您可能需要一些测量时间来为所使用的浏览器获得更正确的帧速率.

还要注意timestamp参数,它requestAnimationFrame是高分辨率时间戳,最小精度为1毫秒,也可用于确定动画的速度和任何浏览器滞后.

  • IE9 +实际上非常快.根据我的经验,有时比FF快. (2认同)