how to save canvas as png image?

241,307

Solution 1

try this:

var canvas = document.getElementById("alpha");
var dataURL = canvas.toDataURL("image/png");
var newTab = window.open('about:blank','image from canvas');
newTab.document.write("<img src='" + dataURL + "' alt='from canvas'/>");

This shows image from canvas on new page, but if you have open popup in new tab setting it shows about:blank in address bar.

EDIT:- though window.open("<img src='"+ canvas.toDataURL('image/png') +"'/>") does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:

window.open(canvas.toDataURL('image/png'));

Solution 2

FileSaver.js should be able to help you here.

var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
    saveAs(blob, "pretty image.png");
});

Solution 3

To accomodate all three points:

  • button
  • save the image as a png file
  • open up the save, open, close dialog box

The file dialog is a setting in the browser.

For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    let dataURL = canvas.toDataURL('image/png');
    let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
    downloadLink.setAttribute('href', url);
    downloadLink.click();
}

Example on Codepen

Another, somewhat cleaner, approach is using Canvas.toBlob():

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    canvas.toBlob(function(blob) {
      let url = URL.createObjectURL(blob);
      downloadLink.setAttribute('href', url);
      downloadLink.click();
    });
}

Example on Codepen

Neither solution is 100% cross browser compatible, so check the client

Solution 4

I used this solution to set the file name:

HTML:

<a href="#" id="downloader" onclick="download()" download="image.png">Download!</a>
<canvas id="canvas"></canvas>

JavaScript:

function download(){
    document.getElementById("downloader").download = "image.png";
    document.getElementById("downloader").href = document.getElementById("canvas").toDataURL("image/png").replace(/^data:image\/[^;]/, 'data:application/octet-stream');
}

Solution 5

I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:

function download(){
        var download = document.getElementById("download");
        var image = document.getElementById("canvas").toDataURL("image/png")
                    .replace("image/png", "image/octet-stream");
        download.setAttribute("href", image);

    }

In the body part of your HTML specify the button:

<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>

This is working and download link looks like a button. Tested in Firefox and Chrome.

Share:
241,307
sneaky
Author by

sneaky

Updated on January 21, 2022

Comments

  • sneaky
    sneaky over 2 years

    I have a canvas element with a drawing in it, and I want to create a button that when clicked on, it will save the image as a png file. So it should open up the save, open, close dialog box...

    I do it using this code

    var canvas = document.getElementById("myCanvas");
    window.open(canvas.toDataURL("image/png"));
    

    But when I test it out in IE9, a new window opens up saying "the web page cannot be displayed" and the url of it is:

    data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAABpCAYAAACd+58xAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAADRwSURBVHhe7V0HgBVF0q7ZJSlJwRxAPUFRD39RFLN34qGnnomoqIjhzBlFPROIgsoZzogR5AQEzJ4BPFAUEUwgJjgQkCQKooggaf/6el6/6ZnpSW/zUn237u5MdXX1172+z6rqaqeEG6VsJet+pDW/vkdrfx3H3yfT2tVzaP26X6hkw1q/BoeI/280/29JwznZxJPUyXtBQBAQBAQBQaBcECjefmi56BWlZYtAeqajx/WokfrJYEqOIikOFRfXoVq161PtOk2odu0t+ectqKiojnrntWhC46QhYOtXfUarl79Ivy9/ldau+h+tX/8b2SbjJ07pWFQy2Uqnp2yXSrQJAoKAICAICALJCAgBS8ao8iTi/UvpSZlBxiwqwWOKimsxCWtEdettR3XqbEfFtRonkrBYArZh3fe0+senadWyEbRm1UzasP53K45ZiFc84RKyVXkbVUYWBAQBQUAQyIqAELCsiFW2fDQpSyZk8UQMMysqKmaPWCOqt8mOVK/eTuQU1YuccCQBW7dyIq38/j5a/fN/ad3a5QGXmqsvLfGKJl0ZCFdONEOPyl5lGV8QEAQEAUGghiMgBKzqLHCeHqVOrILtduF4M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7y4t+WXRw76sfVc42fPV936iJ5+LKrbqTU0P3rA+0dZbEh20L9HJHYj23I2oVrHFT5U5NFnY4m6svUA0Pvo8efbvjCBqtr0nN+IVot4Dkvv1v5aoy/HJcpUpsfI3olffdknV0uWuJfv9kWjkw55VIFAfM073PE4EkqZbEBf9HMTs8C6e3KhHiPbdqzJnKWMLAoJAeSMgHrDyRrj0+rOEGvVoYY9Y0inIeE+YqQ+cqGGj3dgDtvJjC/mKm7BHmG68lGjO+0T
    

    Anyone know how to fix this?

  • sneaky
    sneaky almost 12 years
    it crashes on this command: var w=window.open('about:blank','image from canvas');
  • sneaky
    sneaky almost 12 years
    i changed it to this: var w=window.open('about:blank');, and now the image opens up in a new window, but how do I get it so that its a save close box, i don't want to have to right click the image and hit save as...
  • James Scholes
    James Scholes almost 12 years
    There is a lot that doesn't work in IE9 :-( Quite a bit can be fixed with polyfills but I am afraid this is beyond that. If you can I suggest using Google Chrome Frame for users using IE.
  • James Scholes
    James Scholes over 7 years
    @VagueExplanation toBlob() is not supported on Safari. But a simple polyfill can be found here: developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/…
  • Brannon
    Brannon over 6 years
    This works nicely, except the JavaScript function canvas.toDataUrl(...) should be canvas.toDataURL(...).
  • Mike
    Mike over 6 years
    Unfortunately, in IE 11 it clears the screen and changes the url to: data:image/octet-stream;base64,iVBORw
  • Alan Stewart
    Alan Stewart about 4 years
    After SO much time looking for a solution, THIS is the one that worked for me. On Firefox 76.0.1 (64-bit), which is what I'm using. I should check other browsers but I sure hope that anything up-to-date would still work.