我多次尝试将image.width和image.height分配给另一个变量,但变量的值始终为0.
这是我的代码:
//canvas element
var canvas = document.createElement ('canvas');
var canvasWidth = window.innerWidth ;
var canvasHeight = window.innerHeight;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
//img element
var loadImage = function (src, scale){
var image = document.createElement ('img');
image.onload = function(){
image.width*=scale;
image.height*=scale;
}
image.src=src;
return image;
}
//player function
var Player = function (){
this.image = loadImage("Fish1.png", 1);
this.score = 0;
this.width = this.image.width;
this.height = this.image.height;
this.x = window.innerWidth/2;
this.y= window.innerHeight/2;
}
Player.prototype.update = function (){
}
Player.prototype.render = function (){
//context.drawImage(this.image, this.x, this.y, this.width, this.height);
}
//context
var context = canvas.getContext('2d');
//player object
var player = new Player ();
window.onload = function (){
document.body.appendChild(canvas);
//context.drawImage(player.image, player.x, player.y, 100, 100);
}
你可以看到,在我做了一些谷歌搜索之后,我发现我必须首先使用image.onload加载我的图像,我这样做但我仍然无法分配image.width的值。例如,如果我放置document.write(player.width)或者甚至是document.write(player.image.width),则打印值为0。但后来我尝试在window.onload函数中打印出player.image.width并打印出正确的值。你能告诉我我错过了什么以及如何解决这个问题。
答案 0 :(得分:1)
您仍然在>>加载之前访问图片的尺寸。简单地添加onload
并不能解决您的问题。 加载图片后,您仍然需要访问尺寸
一种解决方案是首先加载图像,然后使用图像创建播放器对象。
您可以使用静态方法提供一个很好的API:
function Player(image) {
this.image = image;
// ...
}
Player.withImage = function(src, scale, done) {
var image = document.createElement('img');
image.onload = function(){
image.width *= scale;
image.height *= scale;
// once the image loaded, we create a new player and pass it to the callback
done(new Player(image));
};
image.src = src;
};
Player.withImage("Fish1.png", 1, function(player) {
// context.drawImage(player.image, player.x, player.y, 100, 100);
});
当然,对于单个玩家来说,这是一个非常简单的例子。您可以将图像加载代码与播放器类分开。如果要加载多个图像,可能需要查看promises。