Skip to content

Instantly share code, notes, and snippets.

@pseudosavant
Last active November 19, 2023 17:14
Show Gist options
  • Save pseudosavant/d27fef8dd880bb420a5c0503b0a9a204 to your computer and use it in GitHub Desktop.
Save pseudosavant/d27fef8dd880bb420a5c0503b0a9a204 to your computer and use it in GitHub Desktop.
async method for creating an object URL from a canvas
const canvasToBlobUrl = (() => {
const canvasToBlobURL = (canvas, type='image/webp', option=0.1) => {
const promise = new Promise(async (resolve) => {
await rAF();
const blob = await canvasToBlob(canvas);
resolve(URL.createObjectURL(blob, type, option));
});
return promise;
}
function canvasToBlob(canvas, type, option) {
const promise = new Promise(async (resolve) => {
await rAF();
resolve(canvas.toBlob(resolve, type, option));
});
return promise;
}
return canvasToBlobURL;
const rAF = () => new Promise((resolve) => requestAnimationFrame(resolve));
})();
/*
Examples:
const dataUrl = await canvasToBlobURL(myCanvas); // Use defaults
const dataUrl = await canvasToBlobURL(myCanvas, 'image/jpeg', 0.75); // JPEG 75% quality
const dataUrl = await canvasToBlobURL(myCanvas, 'image/png'); // PNG, no quality possible
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment