简体   繁体   中英

When new image is created, image.width returns 0

The code below says that spike.image.width = 0 . Why is this? I'm probably missing something that is obvious.

 class Spike { constructor(x = 200, y = 200) { this.x = x; this.y = y; this.image = new Image(); this.image.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSIBO-v6hQoEBhzmZ05mKzgYqrsZ0svgsED7IDR4dIVNxc78uc2"; } } const ctx = document.getElementById("canvas").getContext("2d"); const spike = new Spike; console.log(spike.image.width); 
 <!DOCTYPE html> <html> <head> <link href="css/default.css" rel="stylesheet" /> </head> <body> <canvas id="canvas" width="400" height="600"></canvas> <script src="js/main.js"></script> </body> </html> 

When the console.log fires, the image hasn't fully loaded yet. You have to check for when the image has loaded

const spike = new Spike;
spike.image.onload = function()
{
    console.log(spike.image.width);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM