Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
createImageBitmap polyfill with Blob and ImageData source support
* Safari and Edge polyfill for createImageBitmap
* Support source image types Blob and ImageData.
* From:
* Updated by Yoan Tournade <>
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;
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 () {
img.src = dataURL;
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