问题
So, I am doing an animation (Not on a website/webpage!), that uses Javascript
. For the animation, I use requestAnimationFrame
instead of setInterval
, as setInterval
did not work well enough for what I need.
However, although requestAnimationFrame
works well on decently powered devices, slow devices can't keep up with the standard 60 FPS, thereby slowing down the entire animation time.
Is there a way I can make the animation work under a time frame, and have the FPS vary depending on how well it keeps up? Other ideas are welcome as well.
(Note, I would really prefer not to post code, just take my word about this. I just want ideas)
回答1:
Have a look at this demo: http://jsfiddle.net/q7ckebmh/
function Animate(id, useTime){
var can = document.getElementById(id),
ctx = can.getContext('2d'),
wid = can.width,
hei = can.height,
lst = Date.now(),
rps = 2*Math.PI,
step = rps/60, // Expecting 60fps
ang = 0;
(function draw(){
var dif = Date.now() - lst; // Milliseconds since last we drew.
lst = Date.now();
if (useTime) step = rps * dif/1000; // Allows for variable fps
ang += step; // Increment our placeholder. In the
// case where step is constant, this
// ends up looking "slow" when we
// have less than 60fps.
ctx.clearRect(0,0,wid,hei);
ctx.beginPath();
ctx.arc(wid/2 + Math.cos(ang)*50,hei/2 + Math.sin(ang)*50,
10,0,2*Math.PI);
ctx.fill();
requestAnimationFrame(draw);
})();
}
Animate('can1', false);
Animate('can2', true);
You'll notice that if you resize the frame, the first animation will slow down since it is skipping animation frames.
The second animation doesn't appear to slow down because it bases the circle's position on the time it has been since it was last called. It does look a little choppy, but the position is correct, always.
来源:https://stackoverflow.com/questions/14508085/requestanimationframe-running-slow-on-weak-machines-work-around