Skip to content

Instantly share code, notes, and snippets.

@yiwenl
Last active October 23, 2021 20:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yiwenl/975c705f32139826ca658208966a6bc2 to your computer and use it in GitHub Desktop.
Save yiwenl/975c705f32139826ca658208966a6bc2 to your computer and use it in GitHub Desktop.
// saveImage.js
const dataURLtoBlob = (dataurl) => {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
const saveImage = (canvas, filename) => {
var link = document.createElement("a");
var imgData = canvas.toDataURL({
format: 'png',
multiplier: 4});
var blob = dataURLtoBlob(imgData);
var objurl = URL.createObjectURL(blob);
link.download = `${filename}.png`;
link.href = objurl;
link.click();
};
export { saveImage };
@yiwenl
Copy link
Author

yiwenl commented Sep 6, 2019

When initialize the canvas, if using WebGL need to set preserveDrawingBuffer to true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment