logo

How To Download Canvas as an image

Suppose you have a <canvas/> like this:

<canvas id="canvas" width="5" height="5"></canvas>

This will add a link to download the canvas as an image:

<a
  download="image.png" // downloaded file name
  href="#" // this will be modified by `e.target.href`
  onClick={(e) => {
    const dataURL = document.getElementById('canvas').toDataURL('image/png');
    e.target.href = dataURL;
  }}
>
  Download
</a>

The function is .toDataURL()

canvas.toDataURL(type, encoderOptions);
  • type: default value is image/png
  • encoderOptions: image quality, a number between 0 and 1, default value is 0.92.