Canvas To PNG Download Function JavaScript

Here is a little code snippet to hopefully help you out and keep in your toolbox whenever you may need it. The following code was written in Angular (Typescript). The this.canvas is a template variable.

<canvas #canvas></canvas>

The component utilized the @ViewChild decorator.

@ViewChild('canvas') protected canvas: ElementRef;
download() {
  this.canvas.nativeElement.toBlob((blob: Blob) => {
    const url = URL.createObjectURL(blob); // Create the URL from the blob object
    const a = document.createElement('a'); // Create the anchor tag
    a.href = url; // Assign the URL string to the anchor tag's href attribute
    a.download = 'chart.png'; // Name the image by assigning the anchor tag's download attribute
    document.body.appendChild(a); // Append the anchor tag to the DOM
    a.click(); // Click the anchor tag to trigger the download
    document.body.removeChild(a); // Remove the anchor tag from the DOM
    URL.revokeObjectURL(url); // Release the reference to the ObjectURL
  }, 'image/png', .92);
}

You can see how this function can easily be modified to suit your needs, whether that is in a functional component in React, or my personal favorite, vanilla JavaScript.

Published: January 26, 2021 6:24 pm Categorized in:

No Comments

Share Your Comments

I value your privacy, your email address will not be published or shared.

This site uses Akismet to reduce spam. Learn how your comment data is processed.