Skip to content

Instantly share code, notes, and snippets.

@MonsieurV
Last active February 16, 2021 11:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save MonsieurV/fb640c29084c171b4444184858a91bc7 to your computer and use it in GitHub Desktop.
Save MonsieurV/fb640c29084c171b4444184858a91bc7 to your computer and use it in GitHub Desktop.
createImageBitmap polyfill with Blob and ImageData source support
/*
* Safari and Edge polyfill for createImageBitmap
* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap
*
* Support source image types Blob and ImageData.
*
* From: https://dev.to/nektro/createimagebitmap-polyfill-for-safari-and-edge-228
* Updated by Yoan Tournade <yoan@ytotech.com>
*/
if (!('createImageBitmap' in window)) {
window.createImageBitmap = async function (data) {
return new Promise((resolve,reject) => {
let dataURL;
if (data instanceof Blob) {
dataURL = URL.createObjectURL(data);
} else if (data instanceof ImageData) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = data.width;
canvas.height = data.height;
ctx.putImageData(data,0,0);
dataURL = canvas.toDataURL();
} else {
throw new Error('createImageBitmap does not handle the provided image source type');
}
const img = document.createElement('img');
img.addEventListener('load',function () {
resolve(this);
});
img.src = dataURL;
});
};
}
@Kaiido
Copy link

Kaiido commented Feb 16, 2021

The goal of the ImageBitmap interface is to have the bitmap already decoded when we pass it to the drawer. Going back to an HTMLImageElement doesn't make much sense, you'd be better keeping the HTMLCanvasElement instead.
And don't forget to revoke the blobURIs, depending from where they come from you are possibly creating a memory leak.

Also this "polyfill" misses a lot of createImageBitmap's features like the cropping and resizing options, for the ones who want these, I'm writing a more complete monkey-patch available here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment