Javascript:调整每个事件被触发两次的事件

时间:2014-01-07 00:32:54

标签: javascript html5 canvas

我在JS中有一个“Graphics”对象,我用它作为canvas元素的容器。

图形对象只需要一个画布并设置它的宽度,高度等。

我在resize事件上调用了这个函数:

Graphics.prototype.resize = function(){

   this.canvas.width = (this.canvas.width > window.innerWidth) 
                         ? window.innerWidth : someDefaultVar;

   //And same for width...

  alert(this.canvas.width); //Alert for test purposes
};

假设canvas.width< window.innerWidth和window.innerWidth = 205这是每个调整大小的警报输出:

205

原始宽度

我很困惑为什么它会被调用两次,从而导致画布没有调整大小。

在我的动画循环中,我正在使用该对象:

window.addEventListener("load",Main,false); //Added from comment response, 
                                            //load eventlistener

function Main(){
   var canvas = new Graphics(width, height ..); //Object containing the canvas

   window.addEventListener("resize", OnResize,false); //Add the event listener
                                                       // for resize

   function OnResize(){

      canvas.resize(); //Call the function named above
   }

   function AnimLoop(){

       canvas.draw();
       requestAnimationFrame(AnimLoop);
   }

   AnimLoop(); //Call AnimLoop entering starting the animation
}

有人能发现问题吗?

提前致谢

1 个答案:

答案 0 :(得分:3)

由于各种原因,可能会多次抛出resize事件。你可以做的是实现一个计时器,这样只有当事件没有被抛出时才会触发你的调整大小。

例如:

function Main(){
   var canvas = new Graphics(width, height ..);

   /// add a var in main to hold the timer request id    
   var resizeTimer;

   window.addEventListener("resize", OnResize,false);

   function OnResize(){

      /// reset timeout every time resize is triggered
      /// no need to check the value
      clearTimeout(resizeTimer);

      /// setup timer so that when the delay between events
      /// are higher than 200 ms call resize canvas..
      resizeTimer = setTimout(canvas.resize, 200);
   }

   ...    
}

这里发生的事情是,当调整大小事件触发回调时,它会等到200ms过去(尝试使用此值,这只是一些初始值),然后才会实际调用画布调整大小。这有助于减少画布的负载和更新,并更快地处理事件。

希望这有帮助。

相关问题