如何使用HTML2canvas将img保存到用户本地计算机

问题描述 投票:0回答:5

我正在使用 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>
html2canvas
5个回答
65
投票

注意:这个答案来自 2015 年,并且库已更新。
检查下面的答案以了解替代实现。

尝试一下(请注意,它使用了下载属性。有关支持下载属性的浏览器,请参阅 caniuse 支持表

<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>

47
投票

2018年更新

请注意,在新版本的 Html2Canvas 中,onrendered 选项已被弃用并替换为 Promise。

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


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

基于Krzysztof答案

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 对我来说很有效。


希望这有帮助


8
投票

2024 答案:

<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>

演示

SRC


7
投票

这是转换为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);
        }
      }

2
投票
function saveAs(blob, fileName="pic") {
    const link = document.createElement('a');
    link.download = fileName
    link.href = URL.createObjectURL(blob);
    link.click();
    URL.revokeObjectURL(link.href);
}

Html2Canvas(element).then(canvas => {
    canvas.toBlob((blob)=> {
      saveAs(blob, fileName)
    })
})

© www.soinside.com 2019 - 2024. All rights reserved.