Search code examples
javascriptjqueryhtmlcanvashtml2canvas

Draw specific area to canvas


I'm using html2canvas. Is it possible to capture an specified area of a DIV by specifying x, y coordinates?

Example Fiddle

So basically I'm looking for a way to capture x=10 to x=140 and then y=20 to y=220 area.

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

html2canvas(aaaDiv).then(function(canvas) {
    canvas.id='avatarCanvas';
    ttDiv.appendChild(canvas);
});

Solution

  • html2canvas does not have an API option to clip a portion of its source div, but you can fairly easily do that with the clipping version of context.drawImage:

    <!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){
            // define the area you want to crop
            var x=10;
            var y=20;
            // calc the size -- but no larger than the html2canvas size!
            var width=Math.min(canvas.width,140-10);
            var height=Math.min(canvas.height,220-20);
            // create a new avatarCanvas with the specified size
            var avatarCanvas=document.createElement('canvas');
            avatarCanvas.width=width;
            avatarCanvas.height=height;
            avatarCanvas.id='avatarCanvas';
            // put avatarCanvas into ttDiv
            ttDiv.appendChild(avatarCanvas);
            // use the clipping version of drawImage to draw
            // a clipped portion ofhtml2canvas's canvas onto avatarCanvas
            var avatarCtx=avatarCanvas.getContext('2d');
            avatarCtx.drawImage(canvas,x,y,width,height,0,0,width,height);
        });
    
    }); // 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>