使用画布将图像剪切到图像

时间:2014-09-09 20:14:19

标签: image canvas fabricjs clip

这里有没有人在图像中剪切图像?到目前为止,我已经看到了画布上的剪裁,但都是常规形状(矩形,圆形等等)。如果有人真的这样做会很好。

P.S。使用fabric.js或只是常规画布。

1 个答案:

答案 0 :(得分:2)

当然,您可以使用合成仅在第一张图片存在的位置绘制第二张图片:

ctx.drawImage(image1,0,0);  // this creates the 'mask'
ctx.globalCompositeOperation='source-in';
ctx.drawImage(image2,0,0);  // this image only draws inside the mask

插图:首先绘制的房子图像和第二个草图只在房子像素存在的地方绘制:

enter image description here

示例代码和演示:http://jsfiddle.net/m1erickson/r71d8d8b/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // put the paths to your images in imageURLs[]
    var imageURLs=[];  
    // push all your image urls!
    imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house100x100.png");
    imageURLs.push("https://dl.dropboxusercontent.com/u/139992952/stackoverflow/mower_start.png");

    // the loaded images will be placed in images[]
    var imgs=[];
    var imagesOK=0;
    loadAllImages(start);

    function loadAllImages(callback){
        for (var i=0; i<imageURLs.length; i++) {
            var img = new Image();
            imgs.push(img);
            img.onload = function(){ 
                imagesOK++; 
                if (imagesOK>=imageURLs.length ) {
                    callback();
                }
            };
            img.onerror=function(){alert("image load failed");} 
            img.crossOrigin="anonymous";
            img.src = imageURLs[i];
        }      
    }

    function start(){

        // the imgs[] array now holds fully loaded images
        // the imgs[] are in the same order as imageURLs[]

        ctx.drawImage(imgs[0],50,50);
        ctx.globalCompositeOperation='source-in';
        ctx.drawImage(imgs[1],0,0);

    }

}); // end $(function(){});
</script>
</head>
<body>
    <h4>Second grass image is drawn only where<br>house pixels already existed<br>(Uses 'source-in' compositing)</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
相关问题