将html2canvas图像下载到桌面

我找到了这个https://jsfiddle.net/8ypxW/3/ ,我想知道如何将图像下载到桌面。 我只看到保存png但没有下载,如果有可能你能给我脚本吗?

$(function() { $("#btnSave").click(function() { html2canvas($("#widget"), { onrendered: function(canvas) { theCanvas = canvas; document.body.appendChild(canvas); // Convert and download as image Canvas2Image.saveAsPNG(canvas); $("#img-out").append(canvas); // Clean up //document.body.removeChild(canvas); } }); }); }); 

问题是你的小提琴中的canvas2image.js脚本的错误url。 我创造了一个适当的小提琴,让你看看。 在下面的代码中,您可以看到2个“保存PNG”按钮。 一个是使用Canvas2Image.saveAsPNG函数,但这个方法的一个小问题是你无法给出保存图像的名称。 第二个按钮使用HTML下载属性 ,但并非所有浏览器都支持。

 $(function() { $("#btnSave").click(function() { html2canvas($("#widget"), { onrendered: function(canvas) { Canvas2Image.saveAsPNG(canvas); } }); }); $("#btnSave2").click(function() { html2canvas($("#widget"), { onrendered: function(canvas) { saveAs(canvas.toDataURL(), 'canvas.png'); } }); }); function saveAs(uri, filename) { var link = document.createElement('a'); if (typeof link.download === 'string') { link.href = uri; link.download = filename; //Firefox requires the link to be in the body document.body.appendChild(link); //simulate click link.click(); //remove the link when done document.body.removeChild(link); } else { window.open(uri); } } }); 

小提琴

最好的祝福
克日什托夫

更新2018年

请注意,在新版本的Html2Canvas中 , 不推荐使用 onrendered选项并将其替换为promises。

为了能够将图像下载到用户计算机,您可以使用以下内容:


HTML

    

My content here


Javascript(纯JavaScript)

基于Krzysztof的回答

 document.getElementById("download").addEventListener("click", function() { html2canvas(document.querySelector('#boundary')).then(function(canvas) { console.log(canvas); saveAs(canvas.toDataURL(), 'file-name.png'); }); }); function saveAs(uri, filename) { var link = document.createElement('a'); if (typeof link.download === 'string') { link.href = uri; link.download = filename; //Firefox requires the link to be in the body document.body.appendChild(link); //simulate click link.click(); //remove the link when done document.body.removeChild(link); } else { window.open(uri); } } 

遇到的问题

事实上,我能够下载图像,但它是空白的 ……可能的原因(至少在我的情况下)是内容包装器( id =“#boundary” )没有定义宽度或高度,所以指定内容包装器高度宽度对我来说很有用。