如何使用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>

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些