mozila firefox中的html2canvas冲突

时间:2016-04-21 05:51:57

标签: javascript html2canvas

我正在使用html2canvas libary。代码采用div并将其内容保存为png。它适用于operachrome,但是当我在firefox中运行代码时,它不会将div保存为png。单击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>

2 个答案:

答案 0 :(得分:3)

  

hidden中保留DOM个锚元素,并更新href处理程序中元素的onrendered属性。

$('#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

答案 1 :(得分:3)

您需要在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();
      }
    });