2016-09-22 72 views
1

我想通过javascripts画布从图像剪辑环(即环)。 我已经有了一种方法,但我觉得它太不雅了(我真的不明白为什么这会起作用,为什么它不会导致更小的圆圈)。画布 - 从剪裁的画布中抽象形状

see this jsfiddle

context.drawImage(imageObj, 0, 0, 500, 500); 

    //crop outer circle 
    context2.beginPath(); 
    context2.arc(250, 250, 200, 0, 2 * Math.PI, false); 
    context2.closePath(); 
    context2.clip(); 

    //draw circle 
    context2.drawImage(canvas,0,0); 

    //crop inner circle 
    context2.beginPath(); 
    context2.arc(250, 250, 100, 0, 2 * Math.PI, false); 
    context2.closePath(); 
    context2.clip(); 

    //clear context 2 
    context2.clearRect(0,0,500,500) 

    // finally draw annulus 
    context2.drawImage(canvas2,0,0); 

有没有更好的方式来做到这一点?

+0

我没有得到的目标。你不满意在画布上画画布吗? – Hydro

+0

@TheProHands @TheProHands我想从已剪裁的形状中剪下一个形状(在Photoshop中,您可以将其称为“从选区中减去”),而不需要额外的步骤将临时图像绘制到第二个画布。我想要一个解决方案(或至少希望我的解决方案被解释) – InsOp

回答

3

这确实有效,因为由clip方法调用的裁剪区域会堆叠。

国际海事组织,这确实不是最好的办法,因为你肯定需要在削减之前拨打ctx.save();,之后再拨打ctx.restore(),这是非常繁重的方法。

我的首选方法是使用compositing

var ctx = canvas.getContext('2d'); 
 

 
var imageObj = new Image(); 
 

 
imageObj.onload = function() { 
 

 
    ctx.drawImage(imageObj, 0, 0, 500, 500); 
 
    // keep only the outer circle 
 
    ctx.globalCompositeOperation = 'destination-in'; 
 
    ctx.beginPath(); 
 
    ctx.arc(250, 250, 200, 0, 2 * Math.PI, false); 
 
    ctx.fill(); 
 
    // remove the inner one 
 
    ctx.globalCompositeOperation = 'destination-out'; 
 
    ctx.beginPath(); 
 
    ctx.arc(250, 250, 100, 0, 2 * Math.PI, false); 
 
    ctx.fill(); 
 
    // reset gCO 
 
    ctx.globalCompositeOperation = 'source-over'; 
 

 
}; 
 
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
<canvas id="canvas" width="500" height="500"></canvas>

+0

完美,这就是我搜索的。如果你愿意,你可以编辑我的问题(以及将标题改为更理解的标题),因为我认为其他用户也会觉得这很有用。 – InsOp

+1

@InsOp,不知道这个问题最好的标题是什么......无论如何,很高兴它有帮助。 Ps:其他gCO和订单可以达到相同的结果,玩得开心;-) – Kaiido