我已经在我的页面上创建了画布,但是当我尝试在画布上导入图像时,它没有出现,这里是我使用的代码。 (makeGameArea是我为在网页上制作画布而创建的一个方法,此方法的代码未显示,因为将它放在这里很长)
以下是应该有问题的代码
var myGameArea2 = makeGameArea(700, 150, "myArea", "white");
var myContext2 = myGameArea2.getContext("2d");
var myImage = new drawImage(myContext2, "sonic.gif", 91, 97, 0, 0);
myImage.draw();
function drawImage(ctx, src, width, height, x, y){
this.image = new Image();
this.image.src = src;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.draw = function(){
this.image.onload = function(){
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
}
}
}
我的drawImage()方法有什么问题吗?
答案 0 :(得分:0)
HTMLImage。onload
每src
次设置只会触发一次。
在这里,您将使用draw
方法附加处理程序,我想稍后会调用它。此时,事件已经被触发,因此永远不会被调用,因为除非您重置其src
,否则它不会再次触发。
固定代码块:
function drawImage(ctx, src, width, height, x, y){
this.image = new Image();
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.draw = function(){
ctx.drawImage(this.image, this.x, this.y, this.width, this.height));
};
// if you want it to draw as soon as possible
this.image.onload = this.draw.bind(this);
this.image.src = src;
}