2011-04-08 127 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/