The canvas FPS changes on resizen the screen - Javascript

83 Views Asked by At

so im building a simple particle system, and i wanted to be responsive to the every screen. I use a resize script in orther to addapt the canvas to the whole browser.

the problem is that when you resize the screen, the fps gets higher and higher and the particles fall very fast, I don't know whats the problem!

http://jsfiddle.net/gikdew/J6vLg/5/

 function initialize() {
    // Register an event listener to
    // call the resizeCanvas() function each time 
    // the window is resized.
    window.addEventListener('resize', resizeCanvas, false);

    // Draw canvas border for the first time.
    resizeCanvas();
}

function resizeCanvas() {

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    game();
}


function game() {
    var tick = 0;

 window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / fps);
              };
    })();

    (function animloop(){
        requestAnimFrame(animloop);
        createParticles();
        updateParticles();
        killParticles();
        drawParticles();       

})();
    animloop();
1

There are 1 best solutions below

0
On

It's because you are starting a new loop inside game() every time you resize. As rAF is asynchronous the calls will accumulate each affecting the variables you're using.

If you keep the loop outside you should be fine (you can also use a flag to prevent several runs):

/// this should in global scope:
window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / fps);
              };
    })();

And then the main code:

var isRunning = false;

/// do needed stuff here
function game() {
    var tick = 0;
}

/// call manually the first time before loop starts
game();

/// run loop
(function animloop(){
    requestAnimFrame(animloop);
    createParticles();
    updateParticles();
    killParticles();
    drawParticles();       

})();