Javascript 将 Canvas 元素下载到图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8126623/
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-24 04:47:48  来源:igfitidea点击:

Downloading Canvas element to an image

javascriptcanvasdownload

提问by dchhetri

What are the different ways to save a canvas object?

保存画布对象的不同方法有哪些?

In my research, I've found two approaches:

在我的研究中,我发现了两种方法:

var data = canvas.toDataURL();
var prev = window.location.href;
window.location.href = data.replace("image/png", "image/octet-stream");
window.location.href = prev;

Another way is to take a snapshot.

另一种方法是拍摄快照。

Are there other ways to do this?

还有其他方法可以做到这一点吗?

Is it possible to customize the download filename?

是否可以自定义下载文件名?

采纳答案by frank_neff

The one way to save is exporting as an image... You already found this solution, and it's the best one i think ;)

保存的一种方法是导出为图像...您已经找到了这个解决方案,我认为这是最好的解决方案;)

    var canvas = document.getElementById("mycanvas");
    var img    = canvas.toDataURL("image/png");
    document.write('<img src="'+img+'"/>');

You can use different image types. Change the mimetype in this function:

您可以使用不同的图像类型。更改此函数中的 mimetype:

    canvas.toDataURL("image/jpeg");

An other way to save canvas data (into a PDF) is using the wkhtmltopdf Library

另一种保存画布数据(到 PDF)的方法是使用wkhtmltopdf 库

Cheers. Frank

干杯。坦率

frankneff.ch / @frankneff

frankneff.ch / @frankneff

回答by Ulf Aslak

Solution that requires NO BUTTON:

不需要按钮的解决方案:

var download = function(){
  var link = document.createElement('a');
  link.download = 'filename.png';
  link.href = document.getElementById('canvas').toDataURL()
  link.click();
}

Useful if you have other triggers for downloading, or triggers that you can't easily reference.

如果您有其他下载触发器或您无法轻松引用的触发器,则很有用。

回答by Humberto Molina López

This solution is better:

这个解决方案更好:

function download() {
var download = document.getElementById("download");
var image = document.getElementById("myCanvas").toDataURL("image/png")
    .replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
//download.setAttribute("download","archive.png");
}
<a id="download" download="triangle.png">
<button type="button" onClick="download()">Download</button>
</a>
    
<canvas id="myCanvas" width="720" height="450">Your browser does not support Canvas.</canvas>

回答by Gunjan Patel

var c = document.getElementById("popup");
var link = document.getElementById('cropImageLink');
link.setAttribute('download', 'MintyPaper.png');
link.setAttribute('href', c.toDataURL("image/png").replace("image/png", "image/octet-stream"));
link.click();

I hope these code would be work. But first create Anchor tag in canvas tag whose id is 'cropImageLink'. than after check. but it's not working in IE browser

我希望这些代码会起作用。但首先在 id 为“cropImageLink”的画布标签中创建锚标签。比检查后。但它在 IE 浏览器中不起作用

回答by gillyb

You can use the reimglibrary to do this really easily.

您可以使用reimg库轻松完成此操作。

Converting the canvas to an img : ReImg.fromCanvas(document.getElementById('yourCanvas')).toPng()

将画布转换为 img : ReImg.fromCanvas(document.getElementById('yourCanvas')).toPng()

And downloading this image for the user can be done like this : ReImg.fromCanvas(document.getElementById('canvas')).downloadPng()

为用户下载这个图像可以这样完成: ReImg.fromCanvas(document.getElementById('canvas')).downloadPng()

About giving the file a custom name, if you look into the code of the library (which is veryshort and simple to understand) you'll find that you can change the name.
Here is a link to the specific line: https://github.com/gillyb/reimg/blob/master/reimg.js#L56

关于给文件一个自定义名称,如果您查看库的代码(非常简短且易于理解),您会发现可以更改名称。
这是特定行的链接:https: //github.com/gillyb/reimg/blob/master/reimg.js#L56

回答by ifelse.codes

Try something like this ...

尝试这样的事情......

var downloadCanvasAsImage = function(){

    let canvasImage = document.getElementById('canvas').toDataURL('image/png');

    // this can be used to download any image from webpage to local disk
    let xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function () {
        let a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhr.response);
        a.download = 'image_name.jpg';
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        a.remove()
      };
      xhr.open('GET', canvasImage); // This is to download the canvas Image
      xhr.send();
}

回答by TAHA SULTAN TEMURI

relate to thisand thanks to @kaiido

此相关并感谢@kaiido

I just modified the callback method and it worked ,the callback method mentioned there was not working for me

我刚刚修改了回调方法并且它起作用了,提到的回调方法对我不起作用

var callback = function(blob) {
var a = document.createElement('a');
var saveAs = $('input[name="group1"]:checked').val();


var link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'Image.' + saveAs;
document.body.appendChild(link);
link.click();

};
 function dataURIToBlob(dataURI, callback) {
var binStr = atob(dataURI.split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);

 for (var i = 0; i < len; i++) {
  arr[i] = binStr.charCodeAt(i);
 }

   callback(new Blob([arr]));
 }