[英]Javascript: Resize event being fired twice on each event
我在JS中有一个“图形”对象,用作画布元素的容器。
图形对象只需要容纳一个画布并设置其宽度,高度等。
我在调整大小事件上调用了此函数:
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
}
谁能发现问题?
提前致谢
由于各种原因,可能会多次引发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(使用该值的实验,这只是一些初始值)。 这有助于减少画布的负载和更新,并更快地处理事件。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.