/**
* 根据 URL 获取一张图片,返回 Image(HTMLImageElement)对象
*/
export async function fetchImage(url: string, options?: { crossOrigin?: boolean | string }): Promise {
const img = new Image()
img.decoding = "async"
img.src = url
if (options?.crossOrigin) img.crossOrigin = options?.crossOrigin == true ? "Anonymous" : options?.crossOrigin
const loaded = new Promise((resolve, reject) => {
img.onload = () => resolve()
img.onerror = (e) => {
console.error(e)
reject(Error("[fetchImage] Image load."))
}
})
// 保证图片解码完成
if (img.decode) {
// 来自 squoosh 的兼容性处理
// Nice off-thread way supported in Safari/Chrome.
// Safari throws on decode if the source is SVG.
// https://bugs.webkit.org/show_bug.cgi?id=188347
await img.decode().catch(() => null)
}
await loaded
return img
}