Javascript 如何为浏览器提供按钮的“图像另存为”选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30694433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:36:44  来源:igfitidea点击:

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

javascriptjqueryfabricjs

提问by Pramesh Harshana

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.

我正在做一个画布绘图项目。我将画布转换为图像,然后将该图像另存为“.png”。我必须右键单击图像并选择“将图像另存为”选项。但我想通过一个按钮提供该选项。当我单击按钮时,它应该被保存。

Any example or idea would be appreciated.

任何例子或想法将不胜感激。

This is a js function that converts canvas to png.

这是一个将画布转换为png的js函数。

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

回答by adeneo

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

小提琴

回答by Pramesh Harshana

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

首先为它创建一个按钮
<a href="#" class="button" id="btn-download" download="my-file-name.png">Download</a>

Then add the following in javascript

然后在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!

我为你做了一个例子 看看这个!