When new image is created, image.width returns 0


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.


spike.image.width = 0




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>




1 Answer
1



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


console.log


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

Python Tkinter Error, “Too Early to Create Image”