gpt4 book ai didi

javascript - HTML5 和 JS : Getting Image Width

转载 作者:行者123 更新时间:2023-12-02 16:52:53 25 4
gpt4 key购买 nike

编辑:
我按照 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/

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