2011-04-08 182 views
0

我已经创建了2个形状,圆形和矩形,一个在另一个之上,类似于一个按键锁定。然后,我尝试应用中风,但它抚摸着两个形状。我想要它做的只是抚摸合并的模式,而不是任何交叉点。HTML5 - 画布形状描边

context.beginPath(); 
context.fillStyle = "#ccc"; 
context.arc(115, 550, 12, 0, 2 * Math.PI, false); 
context.moveTo(105, 555); 
context.fillStyle = "#999"; 
context.rect(105, 555, 20, 30); 
context.fill(); 
context.stroke(); 
context.closePath(); 

如果我尝试先画出矩形,然后在弧顶有多余的路径,当你中风,它就像我不得不关闭路径,然后再绘制它。

回答

0

如果您希望路径没有交叉部分,您不能使用矩形和整个圆。

取而代之,您只需绘制圆的一部分并仅绘制矩形的一部分。这应该为你做它:

context.beginPath(); 
context.fillStyle = "#ccc"; 
context.arc(115, 550, 12, 2.5, 2.2 * Math.PI, false); 
context.moveTo(105+20, 555); 
context.fillStyle = "#999"; 
// instead of a rect, we really want three lines 
context.lineTo(105+20,555+30); 
context.lineTo(105,555+30); 
context.lineTo(105,555); 

context.fill(); 
context.stroke(); 
context.closePath(); 
+0

我明白了,世界上没有其他办法合并形状?你必须画出你想要的。干杯。 – fes 2011-04-08 14:18:09

+0

技术上还有其他方法可以达到同样的效果。 你可以用黑色填充Rect和Circle,然后在它们上面填充一个2像素的小矩形和圆。这将达到相同的效果(我认为),根本不使用任何路径。但是如果你想使用路径,你不能相交它们,你必须画出确切的东西。 – 2011-04-08 17:30:29

0

虽然我自己的不规则形状的回答工作,我发现了云教授的实验室项目,解决了我的问题。

此页面为SVG-to-Canvas,将SVG图形解析为画布代码。所以,如果你有一个像Illustrator中的应用程序,使用它可以绘制和保存图形为SVG,那么你就可以解析可用帆布码,只是它们插入。

0

可以使用合成和临时画布。类似的东西:

var canvas=document.getElementById("canvas"); 
var ctx=canvas.getContext("2d"); 
var tempCanvas = document.getElementById('tempCanvas'); 
var tempContext = tempCanvas.getContext('2d'); 
tempContext.save(); 
// clear temp context 
tempContext.clearRect(0, 0, canvas.width, canvas.height); 

// draw all rects with strokes 
tempContext.beginPath(); 
tempContext.strokeStyle='red'; 
tempContext.lineWidth=3; 
tempContext.arc(100, 100, 60, 0, 2 * Math.PI, false); 
tempContext.rect(20,150,100,200); 
tempContext.stroke(); 

// set compositing to erase existing drawings 
// where the new drawings are drawn 

tempContext.globalCompositeOperation='destination-out'; 

// fill all rects 
// This "erases" all but the outline stroke 
tempContext.beginPath(); 
tempContext.fillStyle='blue'; 
tempContext.arc(100, 100, 60, 0, 2 * Math.PI, false); 
tempContext.rect(20,150,100,200); 
tempContext.fill(); 


// draw outlines from tempcanvas into canvas 
ctx.drawImage(tempCanvas, 0, 0); 

// draw into canvas 
ctx.beginPath(); 
ctx.fillStyle='green'; 
ctx.globalAlpha = 0.2; 
ctx.rect(20,150,100,200); 
ctx.arc(100, 100, 60, 0, 2 * Math.PI, false); 
ctx.fill(); 

tempContext.restore(); 

而且一个的jsfiddle:https://jsfiddle.net/EvaF/8to68dtd/2/