I tried multiple times to assign my image.width and image.height to another variable but the value of the variable is always 0.
This is my code:
//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);
}
as u can see, after I did some google searches, I found that I had to first load my images using image.onload, and I did that but I still cannot assign the value of image.width. For example if I put document.write(player.width) or even document.write(player.image.width) the value 0 is printed. But then I tried printing out player.image.width in window.onload function and it prints out the correct value. Can you please tell me what I am missing and how I can solve this problem.