将html2canvas图像下载到桌面



我找到了此https://jsfiddle.net/8ypxw/3/,我想知道如何将image下载到桌面上。我只看到保存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&quot"保存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 的新版本中

要能够将图像下载到用户计算机上,您可以使用类似的内容:


html

<html>
    <head></head>
    <body>
        <div id="boundary">
            <div class="content">
                <p>My content here</p>
            </div>
        </div>
        <button id="download">Download</button>
    </body>
</html>

JavaScript(Plain 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" )没有定义宽度或高度,因此指定高度 width to content> content> content wrapper 做了技巧对我。

最新更新