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");
}
source to share
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.
source to share
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!
source to share