Last active
February 25, 2022 22:27
-
-
Save fronterior/8b2a2c4f72e62e529e6eb91bc1ba6c11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const loadImage = ( | |
| src: string, | |
| { | |
| save = true, | |
| timeout = Infinity, | |
| crossOrigin, | |
| }: Partial<{ | |
| save: boolean; | |
| timeout: number; | |
| crossOrigin: string; | |
| }> = {} | |
| ) => { | |
| const img = new Image(); | |
| return new TPromise((resolve, reject) => { | |
| if (timeout !== Infinity) | |
| setTimeout(() => { | |
| reject(new Error(`Load timeout for [${src}]:${timeout}ms`)); | |
| }, timeout); | |
| img.crossOrigin = crossOrigin; | |
| img.onload = () => { | |
| resolve(save ? img : null); | |
| }; | |
| img.onerror = (err) => { | |
| reject(err); | |
| }; | |
| img.src = src; | |
| }, timeout).catch((err) => { | |
| if (err instanceof TPromise.TimeoutError) img.removeAttribute("src"); | |
| throw err; | |
| }); | |
| }; | |
| // const img = await loadImage("https://picsum.photos/1000/1000?1", { | |
| // timeout: 1, | |
| // }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment