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

标签 javascript html image dom

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

相关文章:

javascript - 在 React 中连接变量和字符串

jQuery .before 和 .after 未按预期运行

javascript - 禁止 IFrame 中的网络连接

java - 如何使图像大小可调

javascript - onMouseover 自定义字典自动解析内容应用工具提示?

javascript - Chrome 开发者工具缓存旧版本的 JavaScript 文件

html - 图像叠加图像(图像悬停)

javascript - Jquery 将类添加到最后 5 个元素

javascript - for 循环在自动完成内不起作用

javascript - 如何创建一个脚本来自动 HTML 中的链接交换?