gpt4 book ai didi

javascript - 创建新图像时,image.width 返回 0

转载 作者:行者123 更新时间:2023-12-01 01:54:58 26 4
gpt4 key购买 nike

下面的代码表示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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com