绘制特定区域 canvas

Draw specific area to canvas

我正在使用 html2canvas。 DIV是否可以通过指定x,y坐标来截取a的指定区域?

Example Fiddle

所以基本上我正在寻找一种方法来捕获 x=10 到 x=140,然后是 y=20 到 y=220 区域。

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

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

html2canvas 没有 API 选项来剪辑其源 div 的一部分,但您可以使用剪辑版本轻松做到这一点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>