0

我正在使用 EaselJS 开发一个 HTML5 应用程序,它使用一个覆盖整个窗口的画布元素来显示其界面。我正在使用以下函数来修复画布边界,以防用户调整窗口大小:

function resizeCanvas(event) {
  if (window.onresize == null) window.onresize = resizeCanvas;
  canvas.width  = document.body.clientWidth;
  canvas.height = document.body.clientHeight;
  stage.update();
}

然而,当画布边界改变时,它的一些元素(createjs.Stage() 对象的子元素)也必须改变。理想情况下,我想resizeCanvas()简单地分派一个事件并让适当的stage.children()对象响应。我尝试在上述函数中添加以下行:stage.dispatchEvent(event)并创建如下形状对象:

var grid = new createjs.Shape(drawGrid());
grid.addEventListener('resize', function(evt) { alert(evt); }, false);
stage.addChild(grid);

然而,这不起作用,似乎我严重误解了事件。

4

1 回答 1

1

addEventListener()侦听对象本身调度的事件,而不是对象接收到的事件,因此您的行:

grid.addEventListener('resize', function(evt) { alert(evt); }, false);

将在调度alert时发送- 事件,而不是在收到事件时,因此您必须使用才能获得警报,在这种情况下..您已经拥有该对象,为什么要调度 evnt,如果您可以调用 size-立即方法 - 在这种情况下就像鸡蛋问题一样,尽管如果网格有孩子在听事件,这将是有意义的。gridresizegrid.dispatchEvent('resize')

如果您真的想在这里处理事件,则必须为要调整大小的每个stage元素添加一个侦听器到中心对象(可能是) ,如下所示:

stage.addEventListener('resize', function(evt) { grid.resize(); });
// the grid-object ofc needs a resize-method that handles the event
// also: anonymous functions make this way a complete hassle, but
// you will very likely need the scope of the 'grid' here...

最后你需要让舞台调度调整大小事件,所以在你这样做之前,stage.update()resizeCanvas()添加:

stage.dispatchEvent('resize');
// optionally you can dispatch with an object that contains additional data

What I would do (and I couldn't tell if this way is better or worse, it's just how I would do it): I would write a recursive method to call a resize-method on every child and their children, started by the stage instead of using events.

于 2013-05-23T09:07:41.017 回答