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

时间:2018-07-01 05:53:22

标签: 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>

1 个答案:

答案 0 :(得分:2)

console.log触发时,图像尚未完全加载。您必须检查图像何时加载

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