How to give browser "save image as" option to button

34.3k views Asked by At

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");
 }
2

There are 2 answers

3
adeneo On BEST ANSWER

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

0
AudioBubble On

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!