clipping image to image using canvas

老子叫甜甜 提交于 2019-12-06 19:49:38

Sure, you can use compositing to draw a second image only where the first image exists:

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

Illustration: House image drawn first and second Grass image is drawn only where house pixels exist:

Example code an a Demo: 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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!