簡體   English   中英

如何清除 HTML5 畫布中的圓弧或圓?

[英]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方法清除圓弧。 這當然會清除該區域中的任何其他像素,因此您必須重新繪制它們。

編輯: MooGoo 在下面給出了更好的答案

您可以使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM