Skip to content

Commit 4833129

Browse files
feat(utils): Add image load function (#77188)
1 parent 8bdf780 commit 4833129

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Fetches and provides an HTMLImageElement from a given URL.
3+
* It validates the URL format before attempting to load the image.
4+
*
5+
* @param {string} url - The URL of the image to fetch and inspect.
6+
* @returns {Promise<HTMLImageElement>}
7+
* A promise that resolves to the HTMLImageElement object representing the loaded image.
8+
*
9+
* If the URL is invalid or the image fails to load, the promise is rejected with an error.
10+
*/
11+
export function fetchImageData(url: string): Promise<HTMLImageElement> {
12+
return new Promise((resolve, reject) => {
13+
const img = new Image();
14+
let isCanceled = false;
15+
16+
img.onload = () => {
17+
if (!isCanceled) {
18+
resolve(img);
19+
}
20+
};
21+
22+
img.onerror = error => {
23+
if (!isCanceled) {
24+
reject(error);
25+
}
26+
};
27+
28+
img.src = url;
29+
30+
return () => {
31+
isCanceled = true;
32+
img.onload = null;
33+
img.onerror = null;
34+
};
35+
});
36+
}

0 commit comments

Comments
 (0)