-
-
Save tatomyr/96a9000c7d23c1e980ccfd37e6b5c4c3 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]> | |
* 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