Image.width and Image.height equal to 0 after I load images (javascript) -


i tried multiple times assign image.width , image.height variable value of variable 0.

this 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 did google searches, found had first load images using image.onload, , did still cannot assign value of image.width. example if put document.write(player.width) or document.write(player.image.width) value 0 printed. tried printing out player.image.width in window.onload function , prints out correct value. can please tell me missing , how can solve problem.

you still accessing image's dimensions before loaded. adding onload not solve problem. still have access dimensions after image loaded


one solution load images first , create player objects image.

you can have static method provides nice 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 image loaded, create new player , pass 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); }); 

of course simple example single player. can keep image loading code separate player class. if have multiple images load, might want promises.


Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -