JavaScript - download canvas as png/jpg file on click

0 points
Created by:

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('#canvas-id');
var anchor = document.createElement('a');
anchor.href = canvas.toDataURL('image/png'); // 'image/jpg' = 'image.png';               // 'image.jpg';


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>

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

  <canvas id="my-canvas" width="200" height="200"></canvas>
  <button onClick="handleClick()">Download image</button>

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

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

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

    drawSquare(30, 30, 100);

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

    // Download canvas (click handler)

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



  1. HTMLCanvasElement.toDataURL() - Web APIs | MDN
  2. - 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.

❤️💻 🙂