2013-11-22 37 views
1

到目前为止,我得到这个:http://jsfiddle.net/Lt7VN/如何剪切/剪切形状并揭示其背后的形状?

enter image description here

但它削减/剪辑红色和黑色rects,而我希望它只是削减黑色矩形,我怎么会去这样做?

context.beginPath(); 

context.rect(20,20,160,200); 
context.fillStyle = "red"; 
context.fill(); 

context.beginPath(); 
context.rect(20,20,150,100); 
context.fillStyle = "black"; 
context.fill(); 

context.globalCompositeOperation = "destination-out"; 

context.beginPath(); 
context.arc(100, 100, 50, 0, 2*Math.PI); 
context.fill(); 
+0

你总是可以画出你的红色矩形到另一个画布和位置顶下一个该第二画布。当然在这个特定的例子中,你可以完全忽略'globalCompositeOperation',只是在矩形上绘制红色圆圈。 – akonsu

+0

@akonsu没有办法用一个单一的画布做到这一点?此外,绘制一个红色圆圈不会对我有用,因为我可能会在黑色矩形下面使用多种颜色的图像或复杂的不规则形状,而不是使用红色矩形。 – 01AutoMonkey

+0

我不认为你可以用一个画布做。 – akonsu

回答

1

可以使用合成1个帆布做到这一点。

  • 绘制黑色矩形
  • 集合成到目的地出其中“擦除”
  • 划出弧线(其擦除黑色矩形的一部分)
  • 集合成到目的地在其上“绘制后面”
  • 绘制红色矩形(它填补了圆弧切矩形后面。

enter image description here

这里的代码和一个小提琴:http://jsfiddle.net/m1erickson/F4dp3/

<!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 context=canvas.getContext("2d"); 

    context.save(); 

    context.beginPath(); 
    context.rect(20,20,150,100); 
    context.fillStyle = "black"; 
    context.fill(); 

    context.globalCompositeOperation = "destination-out"; 

    context.beginPath(); 
    context.arc(100, 100, 50, 0, 2*Math.PI); 
    context.fill(); 

    context.globalCompositeOperation = "destination-over"; 

    context.beginPath(); 
    context.rect(20,20,160,200); 
    context.fillStyle = "red"; 
    context.fill(); 

    context.restore(); 

}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <canvas id="canvas" width=300 height=300></canvas> 
</body> 
</html> 
0

两个画布是唯一的办法,我相信 http://jsfiddle.net/Lt7VN/2/

context1.globalCompositeOperation = 'destination-out'; 

context1.beginPath(); 
context1.arc(100, 100, 50, 0, 2*Math.PI); 
context1.globalAlpha = 1.0; 
context1.fill(); 
+0

如果我使用KineticJS会怎么样?或者,也许从“目的地出去”不同的方法? – 01AutoMonkey

+0

KineticJS使用多个画布。 – akonsu