下面的代码表示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>
最佳答案
当 console.log
触发时,图像尚未完全加载。您必须检查图像何时加载
const spike = new Spike;
spike.image.onload = function()
{
console.log(spike.image.width);
}
关于javascript - 创建新图像时,image.width 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51120769/