How to give the browser "save image as" so the button

I am working on a canvas painting project. I convert the canvas as an image, then 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 this option with 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");
 }

      

+3


source to share


2 answers


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 run the function with a button or insert an anchor in the page and configure it as a button.

FIDDLE

+7


source


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

Then add the following to javascript



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

      

I made you an example Check it out!

+4


source







All Articles