简体   繁体   English

为什么context.clearRect()在requestAnimationFrame循环中不起作用?

[英]Why doesn't context.clearRect() work inside requestAnimationFrame loop?

I have a canvas element on the page that is having a circle drawn and moved on it. 我的页面上有一个canvas元素,上面有一个绘制并移动的圆圈。 The circle is being moved by one pixel in every iteration of the loop. 在循环的每次迭代中,圆都移动了一个像素。 Here is the code. 这是代码。

  function clearPage() { context.clearRect(0,0,300, 150); }; var canvasEl = document.getElementById("main"); var context = canvasEl.getContext('2d'); context.fillStyle = 'red'; context.strokeStyle = 'red'; var x = 0; function moveCircle() { clearPage(); context.arc(x, 75, 20, 0, 2* Math.PI); context.stroke(); x++; window.requestAnimationFrame(moveCircle); } moveCircle(); 
 canvas { border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <title>Canvas Practice</title> </head> <body> <canvas id='main'></canvas> <script src="main.js"></script> </body> </html> 

As is evident, my function clears the page before drawing the new circle. 显而易见,我的函数在绘制新圆之前先清除了页面。 Though when run, you can see that it leaves the previously drawn circles on the page. 尽管运行时,您会看到它在页面上留下了先前绘制的圆圈。 If you were to call the clearPage() function after it finished animating, the whole page would get cleared like expected. 如果要在动画完成后调用clearPage()函数,则整个页面将如预期般被清除。

More than anything, I just want to know why this is happening. 最重要的是,我只想知道为什么会这样。 It doesn't seem to be completely intuitive but my best guess is that it has to do with the behavior of requestAnimationFrame(); 它似乎并不完全直观,但我最大的猜测是它与requestAnimationFrame()的行为有关。

You should use the context.beginPath(); 您应该使用context.beginPath(); before drawing the arc. 在绘制圆弧之前。

The reason is that the arcs are added to to the same path so each command redraws the whole path (see https://www.w3.org/TR/2dcontext/#dom-context-2d-arc ). 原因是将弧添加到同一路径,因此每个命令都会重绘整个路径(请参阅https://www.w3.org/TR/2dcontext/#dom-context-2d-arc )。 Using the beginPath starts a new path for each arc and thus does not redraw the previous ones. 使用beginPath为每个弧线启动一个新路径,因此不会重绘以前的弧线。

 function clearPage() { context.clearRect(0,0,300, 150); }; var canvasEl = document.getElementById("main"); var context = canvasEl.getContext('2d'); context.fillStyle = 'red'; context.strokeStyle = 'red'; var x = 0; function moveCircle() { clearPage(); context.beginPath(); context.arc(x, 75, 20, 0, 2* Math.PI); context.stroke(); x++; window.requestAnimationFrame(moveCircle); } moveCircle(); 
 canvas { border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <title>Canvas Practice</title> </head> <body> <canvas id='main'></canvas> <script src="main.js"></script> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM