我试图通过使用HTML5的类构造函数在TypeScript画布中绘制一只小猫,但我对如何完成任务感到困惑。我已经对代码进行了注释,以显示我试图根据我预期的行为和实际工作的行为所做的事情。非常感谢你的计时器和建议。
module Game {
export class Test {
width: number;
height: number;
cellWidth: number;
cellHeight: number;
canvas: HTMLCanvasElement;
context: CanvasRenderingContext2D;
constructor() {
this.width = 28;
this.height = 31;
this.cellWidth = 20;
this.cellHeight = 20;
this.canvas = <HTMLCanvasElement> document.getElementById("game_canvas");
this.context = this.canvas.getContext("2d");
this.canvas.width = this.width * this.cellWidth;
this.canvas.height = this.height * this.cellHeight;
this.context.fillStyle = "blue";
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
let kitten = new Image();
kitten.src = 'img/kitten.png';
// When trying to draw a kitten in the canvas,
// this will work:
kitten.onload = () => {
this.context.drawImage(kitten, 0, 0);
};
// but this work won't:
//this.context.drawImage(kitten, 0, 0);
/*
I was assuming that by accessing the this.context property
I would have direct access to the canvas and I will be able to use
drawImage to draw the kitten on it; however, that approach
produces no kitten in the canvas.
Only by using the .onload method it works.
I am using the () => notation so that the this inside the block
is referring to the class.
I have seen many JavasScript files in which images are simple drawn
through:
context.drawImage(image, 0, 0);
They are not embedded in .onload
I have tried to Google information but I cannot pinpoint what is
happening.
*/
}
}
}发布于 2016-06-03 12:26:57
根据我在这里的评论,我的答案是:非常简单,因为您声明了一个新的Image()并设置了src,您的drawImage调用无疑会在src被加载之前.如果要使用以前加载的映像(例如从DOM),则不需要创建新的映像和加载
设置src触发加载--在另一个类中执行此操作仍然会使您处于等待加载的时间,而且您无法确定--如果您是正在使用的映像的加载程序,使用onload是防弹的并且必不可少的--唯一的替代方法是当图像已经加载到DOM中(或在其他地方预加载)时,您可能会发现您看到的画布示例被设计为在有关映像的加载时启动。
发布于 2016-05-30 23:32:57
从你的代码:
let kitten = new Image();
kitten.src = 'img/kitten.png';
// When trying to draw a kitten in the canvas,
// this will work:
kitten.onload = () => {
this.context.drawImage(kitten, 0, 0);
};
// but this work won't:
//this.context.drawImage(kitten, 0, 0);使用onload实际上是可以在画布上绘制图像的方法。一个微优化方法是保存一个加载图像的字典,这样如果绘制多个小猫,就可以重用它们。
https://stackoverflow.com/questions/37532790
复制相似问题