Pramesh Harshana Pramesh Harshana - 6 months ago 21
jQuery Question

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

I'm working on a canvas drawing project.i convert the canvas as an image.then i save that image as '.png'.so i have to right click on the image and select the 'save image as' option.but i want to set that option to a button.when i click the button it should be saved.any example or idea would be appreciated.Thank you.

This is the js function that convert canvas to png.

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

}

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

Comments