2010-08-25 97 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(); 
}