html2canvas conflict in mozila firefox

淺唱寂寞╮ 提交于 2019-12-20 06:00:12

问题


I am using html2canvas libary. The code takes a div and save its content as png. It works fine with opera and chrome but while i run the code in firefox it does not save the div as png. No action happens on clicking the download button in firefox.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript" src="js/html2canvas.js"></script>
    <script src="https://rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.js"></script>
  </head>
  <body>
    <div id="html-content-holder">
      Div part to save as png
    </div>
    <input id="btn-Convert-Html2Image" type="button" value="Download" />
    <script>
      $('#btn-Convert-Html2Image').click(function() {
        html2canvas($('#html-content-holder'), {
          onrendered: function(canvas) {
            var a = document.createElement('a');
            a.href = canvas.toDataURL("image/png")
            a.download = 'somefilename.png';
            a.click();
          }
        });
      });
    </script>
  </body>
</html>

回答1:


Keep an hidden anchor element in the DOM and update the href property of the element inside onrendered handler.

$('#btn-Convert-Html2Image').click(function() {
  html2canvas($('#html-content-holder'), {
    onrendered: function(canvas) {
      var a = $('#download').get(0);
      a.href = canvas.toDataURL("image/png")
      a.download = 'somefilename.png';
      a.click();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.js"></script>
<div id="html-content-holder">
  Div part to save as png
</div>
<input id="btn-Convert-Html2Image" type="button" value="Download" />
<a href="" id='download'></a>

Fiddle Demo




回答2:


You need to append the anchor element to the body in Firefox.

html2canvas($('#html-content-holder'), {
      onrendered: function(canvas) {
        var a = document.createElement('a');
        a.href = canvas.toDataURL("image/png")
        a.download = 'somefilename.png';
        document.body.appendChild(a);
        a.click();
      }
    });


来源:https://stackoverflow.com/questions/36760712/html2canvas-conflict-in-mozila-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!