如何使用 HTML2canvas 将图像保存到用户的本地计算机

How to save img to user's local computer using HTML2canvas

我正在使用 HTML2canvas .4.1 渲染 onclick 屏幕截图,并希望将图像保存到用户的本地计算机。如何做到这一点?请注意,我是初学者,所以实际代码对我最有帮助。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="html2canvas.js"></script>

<button id="save_image_locally">download img</button>

   <div id="imagesave">
      <img id='local_image' src='img1.jpg'>
   </div>

<script>

    $('#save_image_locally').click(function(){

            html2canvas($('#imagesave'), 
             {
                onrendered: function (canvas) {
                    var img = canvas.toDataURL("image/png");
                    alert('This will currently open image in a new window called "data:". Instead I want to save to users local computer. Ideally as a jpg instead of png.');
                    window.open(img);
                }
             });
            });

</script>

注意:此答案来自 2015 年,库已更新。
检查下面的答案以了解替代实施方式。

试试这个(注意它使用了下载属性。请参阅 the caniuse support table 了解支持下载属性的浏览器)

<script>

  $('#save_image_locally').click(function(){
    html2canvas($('#imagesave'), 
    {
      onrendered: function (canvas) {
        var a = document.createElement('a');
        // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
        a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
        a.download = 'somefilename.jpg';
        a.click();
      }
    });
  });

</script>

2018 年更新

请注意,在 Html2Canvas 的新版本中,onrendered选项是 deprecated 并替换为承诺。

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


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

基于回答

document.getElementById("download").addEventListener("click", function() {
    
    html2canvas(document.querySelector('#boundary')).then(function(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") 没有定义宽度或高度,因此指定 heightwidth content wrapper 对我有用。


希望这对您有所帮助

这是最新的转PNG代码。

      $("#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);
        }
      }

2022 答案:

<html>
  <head>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
  </head>
  <body>
  <div id="to_save" style="text-align: center; width:300px; height: 300px;"> 
What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

  <button id="download"> Download </button>
    
  <script>
    $( "#download" ).on( "click", function() {
      html2canvas(document.querySelector("#to_save")).then(canvas => {
        canvas.toBlob(function(blob) {
          window.saveAs(blob, 'my_image.jpg');
        });
        });
    });
  </script>
 
  </body>
</html>

DEMO

SRC