我目前正在使用HTML5 Canvas進行一個小實驗項目。爲什麼我的畫布沒有正確清理?
基本上,目前我只是試圖使畫布清晰如預期。我的代碼做的唯一一件事就是生成一條中間被破壞的行。但是,此刻我正在嘗試製作一條線,然後刪除該線並在另一個不同的位置添加另一條線,而不顯示第一條線。
我會想到這個代碼將工作:
poles(20); // this number is the x position at which the line (pole) will be generated
ctx.clearRect(0, 0, WIDTH, HEIGHT);
poles(140)
在所有技術上,這應該只顯示第二極,因爲產生的第一杆後在畫布應該被清除。但仍然顯示兩者。
當我只嘗試:
poles(20);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
畫布是空白的它告訴我,清算工作正常。
我想一兩件事:
poles(20);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
setTimeout(function() {
poles(140)
}, 1000);
在這種情況下,兩柱都出現了,但直到1秒後它告訴我,poles
功能是造成兩者即使功能再產生不循環:
function poles(x) {
var bottomH = getRandomInt(20, 180)
// using seperate rectangles will make a break
rect(40, 220 - bottomH, x, 0); // first section of line
rect(40, bottomH, x, HEIGHT - bottomH); // second section of line
}
我希望有人能向我解釋爲什麼我的poles
功能是使兩個極點的重新出現。您可以查看示例here。 作爲參考,主要代碼:
var canvas = document.getElementById("canvas"),
WIDTH = canvas.width,
HEIGHT = canvas.height;
var ctx = canvas.getContext("2d");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function rect(w, h, x, y) {
ctx.rect(x, y, w, h);
ctx.fill();
}
function poles(x) {
var bottomH = getRandomInt(20, 180); // determine where the line break will be
rect(40, 220 - bottomH, x, 0);
rect(40, bottomH, x, HEIGHT - bottomH);
}
poles(20);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
setTimeout(function() {
poles(140)
}, 1000);
我完全忘了關閉的路徑。你完全正確c:謝謝。我會接受你的建議,避免它! – Shawn31313 2014-11-23 01:43:51
一個更正:不* close *路徑(rect子路徑不能按定義關閉 - 沒有開放結束關閉)。在任何新的路徑操作之前(填充/敲擊之後)使用**'beginPath()**。 – K3N 2014-11-23 07:26:34
@ KenFyrstenberg - 謝謝Ken。很好,重新使用'beginPath()' – enhzflep 2014-11-24 02:25:48