使用html2canvas捕获基础知识

时间:2015-04-10 05:38:18

标签: javascript html5 canvas html2canvas

我正在使用html2canvas。如何捕获DIV aaa并在DIV avatar内的画布tt中打印它?

<div id="aaa">
    aaaaa<br />
    bbbbb
</div>

<div id="tt"> </div>

JS:

html2canvas($('#aaa'), {
        onrendered: function(canvas) {
          var canv = $('<canvas />', { id: "avatar"});
          $('#tt').append(canv);
      var newImg = document.getElementById("avatar");
      newImg.src = canvas.toDataURL();
        }
      });

2 个答案:

答案 0 :(得分:1)

试试这个..

在onrendered事件函数中,您将获得canvas元素,只需将它放在任何您想要的位置。

html2canvas($('#aaa'), {
    onrendered: function(canvas) {
    $(canvas).attr('id','avatar');
    $('#tt').append(canvas);
  }   
});

请参阅此以获取更多信息.. http://html2canvas.hertzen.com/examples.html

答案 1 :(得分:0)

这是一种方式:

https://jsfiddle.net/m1erickson/wtchz972/

<!doctype html>
<html>
<head>
<script src="https://rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
    #avatarCanvas{border:1px solid green;}

</style>
<script>
window.onload=(function(){

    var aaaDiv=document.getElementById('aaa');
    var ttDiv=document.getElementById('tt');

    html2canvas(aaaDiv).then(function(canvas) {
        // assign id:avatarCanvas to canvas 
        canvas.id='avatarCanvas';
        // append canvas to ttDiv
        ttDiv.appendChild(canvas);
    });

}); // end $(function(){});
</script>
</head>
<body>
    <h4>This is 'aaa'</h4>
    <div id="aaa">
        aaaaa
        <br>
        bbbbb
    </div> 
    <h4>This is 'tt'</h4>   
    <div id='tt'></div>
</body>
</html>