javascript - Canvas - 从原型(prototype)中绘制图像

标签 javascript html canvas prototype

我正在使用原型(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/

相关文章:

javascript - 什么 JavaScript RegEx 允许除某些特殊字符外的字母数字字符?

javascript - Canvas 随重力交替形状

javascript fabricjs 过滤器不将过滤后的 Canvas 返回到 url

javascript - 在原型(prototype)中使用数组

javascript - 具有动态输入字段的动态表中的复选框

javascript - nodejs 上的 heredoc

javascript - 尝试使用带有submitHandler的jquery表单验证器提交表单

jQuery .removeAttr ('style' ) 在 .animate() 之后不起作用

javascript - 如何从子 iframe 获取 <title> 以在 index.html 上设置

javascript - 将 HTML Canvas 用于 UI 元素?