Save a canvas as a PNG Using the download attribute

Created at 16-May-2020 , By samar

HTML canvas element  is used to draw 2D shapes using Javascript.  It can also be converted to an image (png, jpeg, etc.) and can be embedded in the HTML page using <img> tag. We use html canvas element  and javascript to convert canvas to image (png, jpg) . There  are the  few steps to convert canvs to image:

1. First we get the html5 canvas and anchor tag (to download  image) .

You can insert below code in  between <body>  </body> tag in your html file

<canvas id="c" width="400" height="280"></canvas>
        <a id="download-canvas" href="#">Download</a>

2. Second we use javascript to draw (shape) element on canvas. and create data url for anchor tag and specify the image name.

Insert below code in between <script></script> tag in your file

(function() {
    var canvas = document.getElementById('c'),
        cxt = canvas.getContext('2d'),
        downloadLink = document.getElementById('download-canvas');
        cxt.fillStyle = 'deepskyblue';
        cxt.fillRect(100, 50, 200, 200);
        cxt.clearRect(150, 100, 100, 100);
       downloadLink.href = canvas.toDataURL(); = "squares.png";

Now your image is ready to download . By simply click on anchor tag you can download your image. 

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.