使用画布将图像剪切为图像 [英] clipping image to image using canvas

查看:105
本文介绍了使用画布将图像剪切为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有没有人在图像中裁剪过图像?到目前为止,我还没有看到有关在画布上裁剪的信息,但是它们都是常规形状(矩形,圆形等).如果有人真的做到了,那就太好了.

Has anyone here have done clipping an image within an image? I've seen so far about clipping on the canvas but are all regular shapes(rectangle, circle, etc...). It would be nice if some have actually done it.

P.S.使用fabric.js或仅使用常规画布.

P.S. with fabric.js or just the regular canvas.

推荐答案

当然,您可以使用合成仅在第一个图像存在的地方绘制第二个图像:

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:

示例代码和演示: 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>

这篇关于使用画布将图像剪切为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆