我正在使用原型(prototype)模式编写一些基本代码。我正在尝试将图像绘制到 Canvas 上,但它不起作用。我已经在 Chrome 中调试了代码,这是因为 image.onload
没有触发。我不相信正在加载图像。
这是控制它的两个函数。
var SimpleGame = function () {
self = this; //Reference to this function
//Canvas
this.canvas = document.createElement("canvas");
this.ctx = this.canvas.getContext("2d");
this.canvas.width = 251;
this.canvas.height = 217;
//Default objects
this.bgReady = false;
this.bgImage = new Image();
};
var simpleProto = SimpleGame.prototype; //Cache the prototype
//Draw the objects on the canvas
simpleProto.draw = function() {
//Draw/ Render the canvas
document.body.appendChild(self.canvas);
//Draw the background
self.bgImage.onload = function() {
self.bgReady = true;
};
self.bgImage.src = "images/background.png";
if(self.bgReady) {
self.ctx.drawImage(self.bgImage, 10, 10);
};
}
知道为什么吗?
最佳答案
您的 if(self.bgReady) 在图像有机会加载之前正在接受测试。
所以自然会为false,drawImage不会被执行。
修复:
将self.ctx.drawImage放在self.bgImage.onload中
祝你的项目好运!
关于javascript - Canvas - 从原型(prototype)中绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275238/