HTML5 Canvas to PNG File

To convert an HTML5 Canvas to a PNG file, you use the canvas.toDataURL() method. This method generates a base64-encoded data URL representing the canvas content as a PNG image. You can then use this data URL to display the image or trigger a file download.

How canvas.toDataURL() Works

The toDataURL() method returns a string containing the canvas image in the specified format. For PNG, the returned string looks like this −

data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....

You can assign this data URL to an <img> tag's src attribute to display the canvas content as a regular image −

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...." />

Downloading Canvas as a PNG File

To let the user download the canvas as a PNG file, create an <a> tag with the download attribute set to the desired filename and the href set to the generated data URL −

<a download="newimg.png" href="data:image/png;base64,...">Download PNG</a>

For server-side downloads, you can set HTTP headers to force a file download −

Content-Disposition: attachment; filename=newimg.png

Complete Working Example

The following example draws a rectangle on a canvas and provides a download link. The data URL is generated dynamically when the user clicks the link, which reduces memory usage since the browser does not hold the data URL in RAM until it is actually needed ?

Example

<!DOCTYPE html>
<html>
<body>
    <canvas id="myCanvas" width="300" height="200"
        style="border:1px solid #ccc;">
    </canvas>
    <br>
    <a id="downloadLink" download="newimg.png" href="#">
        Download as PNG
    </a>

    <script>
        // Draw something on the canvas
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = '#4CAF50';
        ctx.fillRect(50, 30, 200, 140);
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '20px Arial';
        ctx.fillText('Hello Canvas!', 70, 110);

        // Generate data URL on click to save memory
        var link = document.getElementById('downloadLink');
        link.addEventListener('click', function() {
            this.href = canvas.toDataURL('image/png');
        }, false);
    </script>
</body>
</html>

When you open this in a browser, it draws a green rectangle with white text on the canvas. Clicking the "Download as PNG" link generates the PNG data URL and triggers a file download named newimg.png.

Conclusion

Use canvas.toDataURL('image/png') to convert canvas content to a base64-encoded PNG. Pair it with an <a> tag's download attribute to let users save the image as a file. Generate the data URL on click rather than upfront to keep memory usage low.

Updated on: 2026-03-12T23:34:42+05:30

962 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements