2010-08-25 95 views
14

我發現有一個clearRect()方法,但無法找到任何清除圓弧(或整圓)的方法。如何清除HTML5畫布中的圓弧或圓圈?

有什麼辦法清除畫布中的弧線?

+0

一旦你需要清除複雜的形狀,畫布抽象庫可能會有用。這就是爲什麼[我建立了一個](http://kangax.github.com/fabric.js/)。也許它可能會有用。 – kangax 2011-11-26 23:26:30

回答

10

不是,一旦你在畫布上繪製了一些東西,就沒有任何東西可以清除,只是你繪製的像素。 clearRect方法不清除先前繪製的對象,它只是清除參數定義的空間中的像素。如果您知道包含它的矩形,則可以使用clearRect方法清除圓弧。這當然會清除該區域中的任何其他像素,因此您必須重新繪製它們。

編輯:MooGoo has given a much better answer below

+0

這是很好的建議。如果您擔心要清除弧線上的其他內容,請考慮將要繪製的對象分隔到多個畫布上(堆疊在另一個上方)。這樣一來,弧線周圍的小清除並不會消除一些背景內容,並且您仍然可以避免從context.clearRect(0,0,screenWidth,screenHeight)中獲得巨大的性能。 – 2016-09-07 14:45:21

27

沒有clearArc但是你可以使用組合操作來實現同樣的事情

context.globalCompositeOperation = 'destination-out' 

根據MDC此設置的效果

現有內容保持在與新形狀不重疊的位置。

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Compositing

所以用這個模式中的任何填充形狀上最終會消除當前畫布的內容。

+0

謝謝!使用這種方法,我的動畫每幀都從7ms降到0.5ms。 – 2013-10-18 10:11:15

6

您可以使用clearRect()方法擦除畫布的一部分(包括您的弧線),但是當您使用clearRect()和arcs或其他使用beginPath()和closePath()在繪圖時,您也需要在擦除時處理路徑。否則,你可能最終會出現一個褪色的弧形版本。

//draw an arc (in this case, a circle) 
context.moveTo(x, y); 
context.beginPath(); 
context.arc(x,y,radius,0,Math.PI*2,false); 
context.closePath(); 
context.strokeStyle = "#ccc"; 
context.stroke(); 

//now, erase the arc by clearing a rectangle that's slightly larger than the arc 
context.beginPath(); 
context.clearRect(x - radius - 1, y - radius - 1, radius * 2 + 2, radius * 2 + 2); 
context.closePath(); 
0

這裏有一個更新的搗鼓你太(使用clearRect):https://jsfiddle.net/x9ztn3vs/2/

它有一個clearApple功能:

block.prototype.clearApple = function() { 
    ctx.beginPath(); 
    ctx.clearRect(this.x - 6, this.y - 6, 2 * Math.PI, 2 * Math.PI); 
    ctx.closePath(); 
}