Fix for loading SVG in Safari. (#212)

* Fix for loading SVG in Safari.

* Tidier code
This commit is contained in:
Jake Archibald
2018-10-20 13:55:38 +01:00
parent e24d7865ce
commit c82d0d1b88
2 changed files with 11 additions and 9 deletions

View File

@ -1,5 +1,5 @@
interface HTMLImageElement {
decode: () => Promise<void> | undefined;
decode: (() => Promise<void>) | undefined;
}
interface CanvasRenderingContext2D {

View File

@ -90,18 +90,20 @@ export async function blobToImg(blob: Blob): Promise<HTMLImageElement> {
const img = new Image();
img.decoding = 'async';
img.src = url;
const loaded = new Promise((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(Error('Image loading error'));
});
if (img.decode) {
// Nice off-thread way supported in at least Safari.
await img.decode();
} else {
// Main thread decoding :(
await new Promise((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(Error('Image loading error'));
});
// 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);
}
// Always await loaded, as we may have bailed due to the Safari bug above.
await loaded;
return img;
} finally {
URL.revokeObjectURL(url);