[英]How can I clear an arc or circle in HTML5 canvas?
我发现有一个clearRect()
方法,但找不到任何可以清除弧线(或整圆)的方法。
有没有办法清除画布中的弧线?
没有clearArc
但是您可以使用复合操作来实现相同的目的
context.globalCompositeOperation = 'destination-out'
根据 MDC,此设置的效果是
现有内容保留在不与新形状重叠的地方。
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Compositing
因此,任何启用此模式的填充形状最终都会擦除当前画布内容。
这是clearRect()
的循环等效项。 最重要的是根据@moogoo 的回答设置一个复合操作。
var cutCircle = function(context, x, y, radius){
context.globalCompositeOperation = 'destination-out'
context.arc(x, y, radius, 0, Math.PI*2, true);
context.fill();
}
请参阅https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html :
不,一旦您在画布上绘制了一些东西,就没有要清除的对象,只有您绘制的像素。 clearRect
方法不会清除先前绘制的对象,它只是清除参数定义的空间中的像素。 如果您知道包含它的矩形,则可以使用clearRect
方法清除圆弧。 这当然会清除该区域中的任何其他像素,因此您必须重新绘制它们。
您可以使用 clearRect() 方法擦除画布的一部分(包括您的弧线),但是当您将 clearRect() 与弧线或任何其他在绘制时使用过的 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();
确保调用 beginPath()
function animate (){
requestAnimationFrame(animate)
c.clearRect(0,0,canvas.width,canvas.height);
c.beginPath();
c.arc(x,y,40,0,Math.PI * 2,false);
c.strokeStyle='rgba(200,0,0,1)';
c.stroke();
c.fillStyle ='rgba(0,0,0,1)';
c.fillRect(x,y,100,100);
x++
} animate()
在这个答案中归功于@Gabriele Petrioli: 为什么 context.clearRect() 在 requestAnimationFrame 循环中不起作用?
这里也有更新的小提琴(使用 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.