在画布中交换裁剪的图像

时间:2016-03-31 16:59:20

标签: javascript canvas html5-canvas drawimage

我想从图像中交换两个圆形切口并交换它们的位置并将它们绘制到画布上。然而,我有问题,绘制第二个圆形图像。有趣的是在second如果你取消注释它绘制该图像的第一行,否则如果你在函数的末尾抛出它,它就不会绘制(至少在顶部)。如果我注释掉第一个函数,我会在画布上绘制图像。第一个函数总是在第二个函数之前执行。

function first() {
      ctx.drawImage(imgBig, 0, 0);
      ctx.beginPath();
      ctx.arc(imgObj1.x + imgObj1.width / 2, imgObj1.y + imgObj1.width / 2, imgObj1.width / 2, 0, 6.28, false);
      ctx.clip();
      ctx.stroke(); // the outline of circle
      ctx.closePath();
      ctx.drawImage(imgBig, imgObj2.x, imgObj2.y, imgObj2.width, imgObj2.height, imgObj1.x, imgObj1.y, imgObj1.width, imgObj1.height);

function second() {
      // ctx.drawImage(imgCuttingBoard, 0, 0); // this will draw over canvas
      ctx.beginPath();
      ctx.arc(imgObj2.x + imgObj2.width / 2, imgObj2.y + imgObj2.width / 2, imgObj2.width / 2, 0, 6.28, false);
      ctx.clip();
      ctx.closePath();
      ctx.drawImage(imgCuttingBoard, imgObj1.x, imgObj1.y, imgObj1.width, imgObj1.height, imgObj2.x, imgObj2.y,
      imgObj2.width, imgObj2.height); // this doesn't draw on top of the image (might be drawing underneath?)
      // ctx.drawImage(imgCuttingBoard, 0, 0); // this will not draw over canvas here
}  

1 个答案:

答案 0 :(得分:2)

假设您在尝试drawImage之前已将图像时间用于完全加载。您确实使用image.onload并等待图片加载?

然后你的问题很可能会被削减......

context.clip是累积的。如果将一个剪辑(剪辑#1)应用于画布,然后是另一个剪辑(剪辑#2),则生成的剪切区域是剪辑#1和剪辑#2的交集。生成的剪辑不是剪辑#2。

因此,如果要撤消剪辑#1以便可以使用完整剪辑#2,则必须将第一个剪辑包裹在context.savecontext.restore中。

这是使用临时画布

执行此操作的略有不同的方法

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/faces%20no%20background.png";
function start(){
    cw=canvas.width=img.width;
    ch=canvas.height=img.height;
    ctx.drawImage(img,0,0);
    // do the swap
    clipCircle(img,63.5,56,54,203,177);
    clipCircle(img,203,177,54,63.5,56);
}

function clipCircle(img,sourceCX,sourceCY,r,newCX,newCY){
    var c=document.createElement('canvas');
    var cctx=c.getContext('2d');
    c.width=2*r;
    c.height=2*r;
    
    // define an clipping circle 
    cctx.beginPath();
    cctx.arc(r,r,r,0,Math.PI*2);
    // draw the source into the temp canvas
    cctx.drawImage(img,-sourceCX+r,-sourceCY+r);
    // draw the temp canvas onto the main canvas
    ctx.drawImage(c,newCX-r,newCY-r);
}
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }
<h4>Swapped clipping on canvas<br>(top-left swapped with bottom-center)</h4>
<canvas id="canvas" width=300 height=300></canvas>
<h4>Original Image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/faces%20no%20background.png'>