简体   繁体   English

为什么我的代码没有清除HTML5画布?

[英]Why is the HTML5 canvas not clearing in my code?

I am just getting started with Canvas programming and trying to build a small game. 我刚刚开始使用Canvas编程,并尝试构建一个小型游戏。 Below is a sample code that I am trying out. 以下是我正在尝试的示例代码。 My intention is to: 我的意图是:

  1. Create a canvas. 创建一个画布。
  2. Fill it with some background color. 用一些背景色填充它。
  3. Draw a circle. 画一个圆。
  4. Clear the canvas. 清除画布。
  5. Draw another circle in different location. 在不同位置绘制另一个圆。

Here's the code: 这是代码:

 var canvas = document.createElement('canvas'); canvas.width= 400; canvas.height = 400; document.body.appendChild(canvas); var ctx = canvas.getContext('2d'); // 2. Fill background ctx.fillStyle = 'rgb(30,0,0)'; ctx.fillRect(0,0,400,400); // 3. Draw circle ctx.save(); ctx.fillStyle = 'rgba(256,30,30,.8)'; ctx.arc(50,50, 20, 0, Math.PI*2, true); ctx.fill(); ctx.restore(); // 4. Clear Canvas ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.restore(); // 5. Draw another circle ctx.save(); ctx.fillStyle = 'rgba(256,30,30,.8)'; ctx.arc(150,150, 20, 0, Math.PI*2, true); ctx.fill(); ctx.restore(); 

But as you can see, only the background color gets cleared and the first circle remains as it is. 但是如您所见,只有背景颜色被清除,第一个圆圈保持原样。

Why is the above code fails to clear the canvas completely before drawing second circle? 为什么上面的代码在绘制第二个圆之前无法完全清除画布?

If you don't use beginPath before starting a new path, all draw command keeps stacking in the current path. 如果您在开始新路径之前不使用beginPath,则所有draw命令都会将堆栈保留在当前路径中。

What's happening here is that when you fill() the second time, the first circle is still in the current path, so even if the screen was in deed cleared, there are two circles drawn with this single fill() command. 这里发生的是,当您第二次执行fill()时,第一个圆圈仍在当前路径中,因此,即使清除屏幕上的内容,使用此单个fill()命令仍会绘制两个圆圈。

==>> use beginPath() before starting a new path. == >>在开始新路径之前使用beginPath()。

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

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