2014-09-27 74 views
1

我剛剛開始使用Canvas編程並試圖構建一個小遊戲。以下是我正在嘗試的示例代碼。我的意圖是:爲什麼HTML5畫布不能在我的代碼中清除?

  1. 創建畫布。
  2. 用一些背景色填充它。
  3. 畫一個圓。
  4. 清除畫布。
  5. 在不同的位置繪製另一個圓。

下面的代碼:

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();

但正如你所看到的,只有背景色被清除,並在第一圈保持原樣。

爲什麼上面的代碼在繪製第二個圓之前未能完全清除畫布?

回答

1

如果您在開始新路徑之前未使用beginPath,則所有draw命令會在當前路徑中保持堆疊。

這裏發生的事情是,當你第二次填充()時,第一個圓仍然在當前路徑中,所以即使屏幕被清除,也會有兩個圓圈用這個fill()命令。

== >>在開始新路徑之前使用beginPath()。

+0

是的。工作! – Veera 2014-09-27 08:19:07

相關問題