我有绘制到 html5 Canvas 的 Renderer 类,我希望它在调整窗口大小时重新绘制内容。问题是 update() 代码只执行一次 - 在initialize() 内部 - 并且调整窗口大小不会执行任何操作。另一方面,每次调整窗口大小时都会执行 onWindowResized()。那么,错误在哪里呢?
/// <reference path="../lib/easeljs.d.ts" />
/// <reference path="../lib/tweenjs.d.ts" />
/// <reference path="../lib/soundjs.d.ts" />
/// <reference path="../lib/preloadjs.d.ts" />
class Renderer
{
private mStage:createjs.Stage;
private mShape:createjs.Shape;
public initialize (stage:createjs.Stage):void
{
this.mStage = stage;
this.mStage.autoClear = true;
this.update ();
window.onresize = this.onWindowResized;
}
public update ():void
{
if (this.mStage)
{
this.mStage.canvas.width = window.innerWidth;
this.mStage.canvas.height = window.innerHeight;
this.mShape = new createjs.Shape();
this.mShape.graphics.beginFill("#dddddd");
this.mShape.graphics.drawRect(0, 0, this.mStage.canvas.width, this.mStage.canvas.height);
this.mShape.graphics.beginFill("#ff4400");
this.mShape.graphics.drawCircle(this.mStage.canvas.width / 2, this.mStage.canvas.height / 2, 25);
this.mStage.addChild(this.mShape);
this.mStage.update();
}
}
private onWindowResized (event:UIEvent):void
{
this.update();
}
}
最佳答案
这里遇到的问题是,当事件执行时,它将在事件的上下文中(用于调整大小的窗口、用于单击的 DOM 元素、鼠标悬停等),而不是您的类 - 所以 this
不会成为你的类的句柄。
您可以通过使用...来解决它
window.onresize = this.onWindowResized.bind(this);
这是一个 bind
比粗箭头语法更优雅的例子。
关于javascript - 阶段未在 TypeScript 中使用 window.onresize 进行更新 (0.9.1.1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19224244/