Languages
[Edit]
EN

JavaScript - download canvas as png/jpg file on click

0 points
Created by:
Anisha-Kidd
652

In this article, we would like to show you how to download canvas as .png or .jpg file on the button click event using JavaScript.

Quick solution:

var canvas = document.querySelector('#my-canvas');

var anchor = document.createElement('a');
anchor.href = canvas.toDataURL('image/png');  // 'image/jpg'
anchor.download = 'image.png';                // 'image.jpg'
anchor.click();

 

Practical example

In this example, we create an invisible anchor (a) element with href property set to the data URL containing a representation of the image on the canvas. Using the download property, we specify the file name to be downloaded. Then we invoke the download with the click() method.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    #my-canvas { border: 1px solid gray; }

  </style>
</head>
<body>
  <canvas id="my-canvas" width="200" height="200"></canvas>
  <br>
  <button onClick="handleClick()">Download image</button>
  <script>

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');

    // Drawing function --------------------------------------------

    function drawSquare(x, y, side) {
        context.beginPath();
        context.rect(x, y, side, side);  // rect(x, y, width, height)
        context.fillStyle = 'red';
        context.fill();
    }

    drawSquare(50, 50, 100);

    // -------------------------------------------------------------

    // Download canvas (click handler)

    function handleClick() {
        var anchor = document.createElement('a');
        anchor.href = canvas.toDataURL('image/png');  // 'image/jpg'
        anchor.download = 'image.png';                // 'image.jpg'
        anchor.click();
    }

  </script>
</body>
</html>

References

  1. HTMLCanvasElement.toDataURL() - Web APIs | MDN
  2. HTMLAnchorElement.download - Web APIs | MDN

Alternative titles

  1. JavaScript - download created canvas as png/jpg file
  2. JavaScript - download HTML canvas element as png/jpg file
  3. JavaScript - download HTML canvas element as png/jpg image
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join