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

前端之家收集整理的这篇文章主要介绍了如何使用HTML2canvas将img保存到用户的本地计算机前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 HTML2canvas .4.1渲染一个截图,并将图像保存到用户的本地计算机.这怎么可以实现?请注意,我是初学者,所以实际的代码对我来说最有帮助.
<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>

解决方法

尝试这样(请注意,Safari会在同一个标​​签页中打开图片,而不是下载它; Safari中不支持下载属性)
<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>
原文链接:https://www.f2er.com/html/224702.html

猜你在找的HTML相关文章