Search code examples
javascripthtmlcanvashtml2canvas

Capture basics using html2canvas


I'm using html2canvas. How do I capture DIV aaa and print it in canvas avatar inside DIV 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();
        }
      });

Solution

  • Here's one way:

    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>