javascript - HTML5 和 JS : Getting Image Width

标签 javascript html image canvas width

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

编辑结束

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

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;

关于javascript - HTML5 和 JS : Getting Image Width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430188/

相关文章:

javascript - JavaScript 中的调用堆栈大小

python - 从 Django django-rest-framework 的 View 有条件地返回 JSON 或 HTML 响应

c++ - 如何在 C++ 中设计高效的图像缓冲区?

javascript - 在 HTML 标签中查找特定关键字并使用 jquery 进行替换

javascript - 使用 Cypress 在按钮单击时模拟 GET api

html - Bootstrap 3.0 产品轮播

image - 我可以将图像作为文件而不是数据存储在 Firebase 上吗 :url?

jquery - 如何放置全宽背景图像?

javascript - innerHTML 不会在每个 keydown 事件中改变

html - 无法正确引用 div 的子元素