Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve different FPS in requestAnimationFrame on different browsers?

How to solve different FPS in requestAnimationFrame on different browsers?
I am making a 3D game using THREE.js that uses requestAnimationFrame and it is fast on Google Chrome 15.
However, it is really slow on Firefox 6 and really really slow (slower than Firefox) on IE9.
This is really a big problem and I am wondering if there is a solution to that.

Thanks.

like image 511
Derek 朕會功夫 Avatar asked Oct 06 '11 23:10

Derek 朕會功夫


People also ask

How do I set frame rate in requestAnimationFrame?

Using setTimeout inside the rAF method is an easy way. var fps = 30; function draw() { setTimeout(function() { requestAnimationFrame(draw); // ... Code for Drawing the Frame ... }, 1000 / fps); } draw(); Nothing too fancy, simple enough!

Can you have multiple requestAnimationFrame?

Any requests registered before the execution of the next repaint gets added to the frame; there's no limit on how many requests can be included in each frame. The handle returned by requestAnimationFrame is a request ID, unique to that particular request, not a frame ID unique to the frame.

How do I slow down requestAnimationFrame?

Slowing down or cancelling requestAnimationFrame() If your animation requires a different frames per second (up to 60 fps) or simply doesn't require that high a level of refresh rate, you can slow it down by calling requestAnimationFrame inside setTimeout() .

Is requestAnimationFrame asynchronous?

Is requestAnimationFrame asynchronous? As now you know that the rAF is a Web API, that means the callback will be called asynchronously. Unlike setInterval , requestAnimationFrame does not accept delay argument, instead, it only calls the callback function when the browser is ready to perform the next paint operation.


1 Answers

The common thing to do is to create a deltaTime (dt) variable which is then be used as a parameter for every animation/update cycle.

Code is only for visualizing the problem/solution.

// ...
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 ;
}

for any call to the render function you then pass 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
}

item.update(dt) looks like that

//...
var x = this.position.get(x);
x = x + (10*dt); // meaning: x increases 10 units every ms.
this.position.x = x;
like image 123
Mirko Avatar answered Sep 19 '22 10:09

Mirko