requestAnimationFrame running slow on weak machines. Work around?

落爺英雄遲暮 提交于 2019-12-06 17:40:39
Shmiddty

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!