File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments