我发现有一个
clearRect()
方法,但找不到清除弧形(或完整圆)的任何方法。
有没有办法在画布中清除一条弧线?
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()方法擦除画布的一部分(包括您的弧形),但是如果您在绘制时使用了beginPath()和closePath()来绘制弧形或其他任何内容,并使用clearRect()进行擦除,则您需要在擦除时处理路径。否则,您可能仍会看到已经消失的弧形的淡化版本。
//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循环内工作?
这里有一个更新的 fiddle(使用 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();
}