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.
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!
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.
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? 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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With