代码中的 whImage
函数是同步的,它使用了 onload
事件来等待图像加载完成后再获取它的宽高。但是,在获取宽高之前函数就已经返回了,因此它会返回 W / H
的初始值,这个值并不是图像的真实宽高比。
为了实现异步获取图像宽高比,我们可以使用 Promise
对象来封装这个过程。在这个过程中,我们可以使用 resolve
函数来返回结果,同时,由于图像加载是异步的,我们需要等待 onload
事件触发后再执行 resolve
函数。
代码示例:
const whImage = (url: any) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => {
const W = img.width;
const H = img.height;
const aspectRatio = W / H;
resolve(aspectRatio);
};
img.onerror = () => {
reject(new Error("Failed to load image"));
};
});
};
注意,我们将 whImage
函数改成了返回一个 Promise
对象。在图像加载完成后,我们通过调用 resolve
函数来返回宽高比,并在发生错误时调用 reject
函数抛出错误。这样,在使用 whImage
函数时,我们可以使用 Promise.then
方法来获取它返回的宽高比。例如:
whImage("/path/to/image.jpg").then(aspectRatio => {
console.log("Aspect ratio:", aspectRatio);
}).catch(error => {
console.error(error);
});
通过这种方式,我们就可以实现异步获取图像的宽高比。