I am attempting to download a large canvas image (several thousand pixels height and width) on the click of a button using toBlob
in the following code, which doesn't seem to work:
document.getElementById("download_button").onclick = function() {
var link = document.createElement("a");
link.download = "image.png";
canvas.toBlob(function(blob){
link.href = URL.createObjectURL(blob);
console.log(blob);
},'image/png');
console.log(link.href);
link.click();
}
console.log(blob)
in the callback function returns: Blob {size: 64452, type: "image/png"}
But console.log(link.href)
returns nothing.
Am I not using .createObjectURL
correctly?
I used to work with toDataURL
, but it stopped working above a certain canvas size. And this post canvas.toDataURL() download size limit suggested to try toBlob
.
If you wish to make the user download the file as it is saved you can do the following: var canvas = document. getElementById("mycanvas"); var image = canvas. toDataURL("image/png").
toBlob() method creates a Blob object representing the image contained in the canvas. This file may be cached on the disk or stored in memory at the discretion of the user agent. The desired file format and image quality may be specified.
function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.
Your code is fine.. just use it at the right time :)
canvas.toBlob(function(blob){
link.href = URL.createObjectURL(blob);
console.log(blob);
console.log(link.href); // this line should be here
},'image/png');
My solution to the problem:
async function getImage({
canvas,
width,
height,
mime = 'image/jpeg',
quality = 0.8,
}) {
return new Promise(resolve => {
const tmpCanvas = document.createElement('canvas');
tmpCanvas.width = width;
tmpCanvas.height = height;
const ctx = tmpCanvas.getContext('2d');
ctx.drawImage(
canvas,
0,
0,
canvas.width,
canvas.height,
0,
0,
width,
height,
);
tmpCanvas.toBlob(resolve, mime, quality);
});
}
const photo = await getImage({ canvas, width: 500, height: 500 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With