canvas 'requestAnimFrame' is slow when any event fire

546 Views Asked by At

I got a problem in drawing on canvas. the problem is that when some event fire, the 'requestAnimFrame' is slow.

http://jsfiddle.net/pAjYC/4/

You can see a time between current drawing and next drawing.

just type a little bit long text on any textbox. you will see an high gap time when you type.

when you type on textbox in fsfiddle, it check the color of text.

it take a little bit time.for example, type 'v' or 'var', in my case, the gap time change 16 to 58. or select source code by dragging, it take a time. the reason might be the access of DOM or some screen changed.

but that would be not all, i am making a game with socket.io .when game receive a socekt, the gap time is 100ms or more. but the socket function just takes 10ms or 20ms.

it is critical issue in a game programming.

is there anyway to solve it?

2

There are 2 best solutions below

1
On

the requestAnimFrame isn't slow - it's your calculations that are slow look here:

http://jsfiddle.net/FwynN/

0
On

You'll want to use Erik Möller's updated version of that shim rather than Paul Irish's:

(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = 
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}())

I'm not sure if that fixes the problem, though...