How-to
    How To Add Google AdSense To Your Website
    How To Download Canvas as an image
    How To Embed Youtube Videos
    How To Host NodeJS Apps
    How To Host Static Websites On Amazon AWS EC2
    How To Host Static Websites On Amazon AWS S3
    How To Host Static Websites On GCP Cloud Storage
    How To Install Node.js
    How to Speed Up IntelliJ IDEA / Clion
    How to safely store API Keys

How To Download Canvas as an image

Updated: 2022-03-19

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.