2013-07-31 29 views
0

HTML5畫布:我正在尋找圍繞組合路徑繪製單筆畫的方法。HTML5畫布:圍繞組合區域的單筆畫

例如,如果我有兩個重疊的圓圈,我不希望有兩個重疊的圓圈招,但兩個圓的組合區域圍繞一個單招..

任何機會是什麼?

回答

2

可以通過使用globalCompositeOperation來完成。有多種方法可以繪製形狀他們的自我,但這裏是一個辦法,導致這(兩個 矩形 圈在演示):

enter image description here

  • 第1步:設置正常帆布
  • 第2步:設置屏幕外的畫布

更新不知道我怎麼能錯過顯而易見的,但你當然可以只中風首先,然後用複合模式和填充來打一個整體 - 快得多(我猜想當我提出偏移重繪時,我的腦海中有圖像)。

離屏畫布的原因是,如果你在主畫布上已經有背景的東西。如果我們打洞的話,這將被刪除。如果無所不有沒有問題畫這一個單一的畫布 - 更新代碼:

/// some regions 
var rect = [ [20, 20, 200, 200], [100, 100, 200,200] ], 

/// ox = off-screen context 
ox.strokeStyle = '#fff'; 
ox.lineWidth = 3 * 2; /// x2 as half will be gone when we punch hole 

/// stroke outlines 
for(; r = rect[i]; i++) { 
    o = r[2] * 0.5; 
    ox.beginPath(); 
    ox.arc(r[0] + o, r[1] + o, o, 0, 2 * Math.PI); 
    ox.stroke(); 
} 

/// punch hole with composite mode and fill 
ox.globalCompositeOperation = 'destination-out';  
for(i = 0; r = rect[i]; i++) { 
    o = r[2] * 0.5; 
    ox.beginPath(); 
    ox.arc(r[0] + o, r[1] + o, o, 0, 2 * Math.PI); 
    ox.fill(); 
} 

/// draw result to main canvas 
/// ctx = main context, ocanvas = off-screen canvas 
ctx.drawImage(ocanvas, 0, 0); 

(Animated) online demo using this optimized version

我會離開,因爲它可以用於圖像的舊代碼,可以」 t被撫摸 -

現在繪製形狀填充到離屏畫布。繪製您想要輪廓所在的顏色。

/// some regions 
var rect = [ [20, 20, 200, 200], [100, 100, 200,200] ], 

/// ox = off-screen canvas 
ox.fillStyle = '#fff'; 

/// draw the array with circes 
for(; r = rect[i]; i++) { 
    var o = r[2] * 0.5; 
    ox.beginPath(); //use this here - arcs are currently buggy 
    ox.arc(r[0] + o, r[1] + o, o, 0, 2 * Math.PI); 
    ox.fill(); //.. and here 
} 

現在將形狀的緩存圖像繪製回主畫布。形狀必須有輕微的在每個方向偏移繪製 - 這一步將創建輪廓:

/// ctx = main context, ocanvas = off-screen canvas 
ctx.drawImage(ocanvas, -1, -1); 
ctx.drawImage(ocanvas, 1, -1); 
ctx.drawImage(ocanvas, 1, -1); 
ctx.drawImage(ocanvas, 1, 1); 
ctx.drawImage(ocanvas, -1, 1); 
ctx.drawImage(ocanvas, 1, 1); 
ctx.drawImage(ocanvas, -1, -1); 
ctx.drawImage(ocanvas, -1, 1); 

最後,我們衝在填充形狀的「洞」,使之透明使用globalCompositeOperation +一個大綱在0戰平最終偏移位置:

ctx.globalCompositeOperation = 'destination-out'; 
ctx.drawImage(ocanvas, 0, 0); 

ONLINE DEMO

爲了使邊框較厚強制當您將圖形繪製回主畫布時,增加偏移量。

+0

對於它的赫克,動畫版:http://jsfiddle.net/AbdiasSoftware/c3VWD/ – K3N

+0

我張貼我目前的解決方案一個新的答案,因爲在評論中的代碼格式不是那麼好.. – lrsjng

0

這是我目前的解決方案。不需要第二個畫布,更容易實現。它仍然採用了肯的主意,用globalCompositeOperation

context.lineWidth = 2; 
context.stroke(); 
var prev = context.globalCompositeOperation; 
context.globalCompositeOperation = "destination-out"; 
context.fill(); 
context.globalCompositeOperation = prev;