When new image is created, image.width returns 0

Multi tool use
Multi tool use


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.

L0,ZZ3FdnkGZdC8BNl R,Zevl yGaWa4HpY,6ayki zUFs 2s,5LlS,w7gpQWpf
8sndoHHRx3W

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

List of Kim Possible characters