Last active
February 16, 2021 11:04
-
-
Save MonsieurV/fb640c29084c171b4444184858a91bc7 to your computer and use it in GitHub Desktop.
createImageBitmap polyfill with Blob and ImageData source support
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
/* | |
* 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 <[email protected]> | |
*/ | |
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; | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.