如何使用HTML2canvas将img保存到用户的本地计算机 [英] How to save img to user's local computer using HTML2canvas

查看:377
本文介绍了如何使用HTML2canvas将img保存到用户的本地计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm rendering a screenshot onclick with HTML2canvas .4.1 and want to save the image to user's local computer. How can this be accomplished? Please note that I'm a beginner, so actual code will be most helpful to me.

<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年,并且库已更新.
请查看下面的答案以了解其他实现方式.

NOTE: this answer is from 2015 and the library has been updated.
Check the answers below for alternate implementations.

尝试此操作(请注意,它利用了download属性.请参见 caniuse支持表对于支持下载属性的浏览器)

Try this (Note that it makes use of the download attribute. See the caniuse support table for browsers that support the download attribute)

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

这篇关于如何使用HTML2canvas将img保存到用户的本地计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆