Skip to content

Instantly share code, notes, and snippets.

@tatomyr
Forked from MonsieurV/createImageBitmap.js
Last active July 6, 2019 11:39
Show Gist options
  • Save tatomyr/96a9000c7d23c1e980ccfd37e6b5c4c3 to your computer and use it in GitHub Desktop.
Save tatomyr/96a9000c7d23c1e980ccfd37e6b5c4c3 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>
* Updated by Andrew Tatomyr
*/
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 || data instanceof Image) {
console.log(data, data instanceof ImageData, data instanceof Image)
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = data.width
canvas.height = data.height
if (data instanceof ImageData) {
ctx.putImageData(data, 0, 0)
} else if (data instanceof Image) {
ctx.drawImage(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