绘制特定区域到画布

时间:2015-04-10 14:19:17

标签: javascript jquery html5 canvas html2canvas

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

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);
});

1 个答案:

答案 0 :(得分:1)

html2canvas没有用于剪辑其源div的一部分的API选项,但您可以使用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>