8

I'm working on a canvas drawing project. I convert the canvas as an image, then I save that image as '.png'. I have to right click on the image and select the 'save image as' option. But I want to provide that option through a button. When I click the button it should be saved.

Any example or idea would be appreciated.

This is a js function that converts canvas to png.

 function save2()
 {
   window.open(canvas.toDataURL('image/png'));
   var gh=(canvas.toDataURL('png'));
   alert("converted");
 }
demongolem
  • 9,474
  • 36
  • 90
  • 105
Pramesh Harshana
  • 143
  • 2
  • 2
  • 8
  • 1
    Check [this](http://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript) out. Just add the button with JS. – Okku Jun 07 '15 at 14:13
  • https://api.jquery.com/click/ – jmargolisvt Jun 07 '15 at 14:14

2 Answers2

20

In modern browser you can use the download attribute

function save2() {
    window.open(canvas.toDataURL('image/png'));
    var gh = canvas.toDataURL('png');

    var a  = document.createElement('a');
    a.href = gh;
    a.download = 'image.png';

    a.click()
}

just trigger the function from a button, or insert the anchor in the page and style it as a button.

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thank you. It worked.How to change the download location?By default it's download to the Downloads folder in (C:) partition. – Pramesh Harshana Jun 07 '15 at 15:51
  • Not sure you can, you can only specify the filename, not the location, that's up to the user – adeneo Jun 07 '15 at 17:02
  • This doesn't work on Safari (tested it on 9). In my case this opens 2 tabs, the browser hangs for a couple of seconds and no download is fired. It work on Chrome (49) – Aico Klein Ovink Mar 21 '16 at 13:36
6

First create a button for it
<a href="#" class="button" id="btn-download" download="my-file-name.png">Download</a>

Then add the following in javascript

var button = document.getElementById('btn-download');
button.addEventListener('click', function (e) {
    var dataURL = canvas.toDataURL('image/png');
    button.href = dataURL;
});

I have made an example for you Check this out!

VK Da NINJA
  • 510
  • 7
  • 19