2013-07-06 21 views
1

我遇到了.rect()的問題。 我使用.drawImage(canvas...)創建了一個網格,並且每當我.stroke()時,它都會再次出現。我怎樣才能完全刪除那個矩形?Rectangle不斷出現在context.clearRect()後面;

問候


Working jsFiddle


var canvas = document.getElementById('board'); 
var context = canvas.getContext('2d'), 

    wt = canvas.width, 
    ht = canvas.height; 

canvas.onmousedown = function (e) { 
    e.preventDefault(); // disabling selecting 
    context.strokeStyle = "red"; 
    context.lineWidth = 1; 
    context.rect(wt/2 - 50, ht/2 - 100, 100, 200); 
    context.fillText("<- why is it here? didn't \"clearRect()\" delete it?", 8, 8); 
    context.stroke(); 
}; 

function grid() { 
    var h = 2.5, 
     p = 2.5; 
    context.rect(0.5, 0.5, 5, 5); 
    context.strokeStyle = "#f0f0f0"; 
    context.stroke(); // creating a 5x5 small rectangle in top left corner 
    for (i = 0; i < wt; i += p) { 
     p *= 2; 
     context.drawImage(canvas, p, 0); // replicating it horizontally... 
    } 
    for (i = 0; i < ht; i += h) { 
     h *= 2; 
     context.drawImage(canvas, 0, h); // ... and vertically 
    } 
    context.clearRect(0, 0, 5, 5); // here I am deleting that stroke, because I don't need it anymore 
    context.drawImage(canvas, 0, 55, 5.5, 5.5, 0, 0, 5.5, 5.5); // drawing it with drawImage(); 
} 
grid(); 
+0

問題應該有它的身體代碼,而不是鏈接 –

+0

@JuanMendes固定,謝謝 – VixinG

回答

3

clearRect清除畫布的一部分,你與rect繪製的路徑不是一部分。撥打電話號碼beginPath()可以清除應用中風時包含的前rect

See this updated example

+0

我剛剛發現我可以使用'strokeRect'爲簡單的圖紙,而不使用'beginPath()'。非常感謝您快速回答! – VixinG