2013-12-07 57 views
-1

所以即時建立一個簡單的粒子系統,並且我想要對每個屏幕做出響應。我在orther中使用調整大小腳本來將畫布添加到整個瀏覽器。畫布上的FPS改變了屏幕的變化 - Javascript

問題是,當你調整屏幕大小時,fps越來越高,粒子下降速度非常快,我不知道最新的問題!

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

這是因爲你每次調整的時間內開始一個game()新的循環。由於rAF是異步的,調用會累積每個影響你正在使用的變量。

如果保持外循環,你應該罰款(你也可以使用一個標誌,以防止在幾個程):

/// 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); 
       }; 
    })(); 

然後主代碼:

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();  

})();