diff --git a/src/lib/util.ts b/src/lib/util.ts index 518f8d59..4e974782 100644 --- a/src/lib/util.ts +++ b/src/lib/util.ts @@ -30,7 +30,28 @@ export async function canvasEncode(data: ImageData, type: string, quality?: numb if (!ctx) throw Error('Canvas not initialized'); ctx.putImageData(data, 0, 0); - const blob = await new Promise(r => canvas.toBlob(r, type, quality)); + let blob: Blob | null; + + if ('toBlob' in canvas) { + blob = await new Promise(r => canvas.toBlob(r, type, quality)); + } else { + // Welcome to Edge. + // TypeScript thinks `canvas` is 'never', so it needs casting. + const dataUrl = (canvas as HTMLCanvasElement).toDataURL(type, quality); + const result = /data:([^;]+);base64,(.*)$/.exec(dataUrl); + + if (!result) throw Error('Data URL reading failed'); + + const outputType = result[1]; + const binaryStr = atob(result[2]); + const data = new Uint8Array(binaryStr.length); + + for (let i = 0; i < data.length; i += 1) { + data[i] = binaryStr.charCodeAt(i); + } + + blob = new Blob([data], { type: outputType }); + } if (!blob) throw Error('Encoding failed'); return blob;