【问题标题】:The canvas FPS changes on resizen the screen - Javascript画布 FPS 在调整屏幕大小时发生变化 - Javascript
【发布时间】:2013-12-07 19:37:20
【问题描述】:

所以我正在构建一个简单的粒子系统,我想响应每个屏幕。我使用调整大小脚本将画布添加到整个浏览器。

问题是,当你调整屏幕大小时,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();

【问题讨论】:

    标签: javascript html canvas resize particles


    【解决方案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();       
    
    })();
    

    【讨论】:

      猜你喜欢
      • 2014-06-20
      • 2015-08-31
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多