Edge encode fix (#211)

* No canvas.toBlob in Edge.

* pffft
This commit is contained in:
Jake Archibald
2018-10-20 13:51:22 +01:00
parent c82d0d1b88
commit 02b0c022ca

View File

@@ -30,7 +30,28 @@ export async function canvasEncode(data: ImageData, type: string, quality?: numb
if (!ctx) throw Error('Canvas not initialized'); if (!ctx) throw Error('Canvas not initialized');
ctx.putImageData(data, 0, 0); ctx.putImageData(data, 0, 0);
const blob = await new Promise<Blob | null>(r => canvas.toBlob(r, type, quality)); let blob: Blob | null;
if ('toBlob' in canvas) {
blob = await new Promise<Blob | null>(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'); if (!blob) throw Error('Encoding failed');
return blob; return blob;