Javascript HTML5&;JS:获取图像宽度

Javascript HTML5&;JS:获取图像宽度,javascript,html,image,canvas,width,Javascript,Html,Image,Canvas,Width,编辑: 我按照马克的建议解决了我的问题。 当然,加载后需要引用图像。通过使用“.onload”函数,我获得了这个。然后,为了引用图像,我只需键入“this.width”,因为我在图像的范围内。 编辑结束 我的画布对象必须绘制各种图像。这些图像基本上是对象的视觉效果。 当尝试获取图像的宽度时,我得到了一个糟糕的零: this.image = new Image(); // src is a parameter to the constructor which this code is run in

编辑:
我按照马克的建议解决了我的问题。 当然,加载后需要引用图像。通过使用“.onload”函数,我获得了这个。然后,为了引用图像,我只需键入“this.width”,因为我在图像的范围内。

编辑结束

我的画布对象必须绘制各种图像。这些图像基本上是对象的视觉效果。 当尝试获取图像的宽度时,我得到了一个糟糕的零:

this.image = new Image();
// src is a parameter to the constructor which this code is run in.
this.image.src = src;
console.log(this.image.width);
正如我所解释的,这段代码返回零

到目前为止,我知道返回的宽度是基于图像的初始构造函数--
在本例中是“new image();”部分 因此,如果没有插入任何内容作为参数,则该值将计为零

但是,如果我将例如:

this.image = new Image(2, 2);
。。“this.image.width”的返回值为2


我的问题是:如何在加载图像之前不知道宽度的情况下引用宽度?

您的图像大小在完全加载之前是未知的,并且由于它是异步加载的,因此在加载之后不立即知道大小。src

设置.onload回调,并将任何需要宽度、高度的代码放入该回调中:

// new-up an image
this.image = new Image();

// set the callback for when the image is fully loaded
this.image.onload=function(){

    // the image is loaded and it's actual size is now known
    console.log(this.width);

}

// src is a parameter to the constructor which this code is run in.
this.image.src = src;

我已经试过了,然后我得到了:“无法读取未定义的属性‘宽度’”。此外,如果我还没有定义我正在使用的图像,则无法知道图像的大小?哎哟,我的糟糕
在内部。onload指的是图像对象。我已经更正了我的答案。对不起!哦,太好了!工作起来很有魅力。谢谢!