Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading canvas image using toBlob

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.

like image 838
tvoirand Avatar asked Jun 15 '17 12:06

tvoirand


People also ask

How do I export a canvas image?

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").

What is canvas toBlob?

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.

How do I convert a canvas object to an image?

function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.


2 Answers

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');
like image 70
ymz Avatar answered Sep 23 '22 01:09

ymz


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 });
like image 31
s.meijer Avatar answered Sep 25 '22 01:09

s.meijer