2012-10-30 70 views
0

我繪製兩個圖像。一個說「1x10」,另一個說「10x10」。基本上,當用戶點擊圖像時,我畫了一個由9條垂直線或9條水平線和9條垂直線所劃分的相同方形的正方形。代碼如下:clearRect不會擦除最後一行

canvas.addEventListener('click',ProcessClick,false); 
function ProcessClick(toi){ 
    var posx = toi.layerX; 
    var posy = toi.layerY; 
    if(toi.layerX == undefined || toi.layerY == undefined){ 
     posx = toi.offsetX; 
     posy = toi.offsetY; 
    } 
    if(posx>170 && posx<320 && posy>320 && posy<370){ 
     rect1x10(); 
    } 
    if(posx>470 && posx<620 && posy>320 && posy<370){ 
     rect10x10(); 
    } 
}//ProcessClick 

rect1x10 = function(){ 
    ctx.strokeStyle = "blue"; 
    ctx.fillStyle = "white"; 
    ctx.clearRect(200, 375, 355, 325); 
    ctx.rect(240, 390, 300, 300); 
    ctx.fill(); 
    ctx.lineWidth = 2; 
    ctx.stroke(); 
    ctx.lineWidth = 1; 
    var lineX = 270.5; 
    for (i = 0; i <= 8; i++){ 
     ctx.beginPath(); 
     ctx.moveTo(lineX, 390); 
     ctx.lineTo(lineX, 690); 
     ctx.stroke(); 
     lineX += 30; 
    } 
}//rect1x10 

rect10x10 = function(){ 
    ctx.strokeStyle = "blue"; 
    ctx.fillStyle = "white"; 
    ctx.clearRect(200, 375, 355, 325); 
    ctx.rect(240, 390, 300, 300); 
    ctx.fill(); 
    ctx.lineWidth = 2; 
    ctx.stroke(); 
    ctx.lineWidth = 1; 
    var lineX = 270.5; 
    for (i = 0; i <= 8; i++){ 
     ctx.beginPath(); 
     ctx.moveTo(lineX, 390); 
     ctx.lineTo(lineX, 690); 
     ctx.stroke(); 
     lineX += 30; 
    } 
    var lineY = 420.5; 
    for (i = 0; i <= 8; i++){ 
     ctx.beginPath(); 
     ctx.moveTo(240, lineY); 
     ctx.lineTo(540, lineY); 
     ctx.stroke(); 
     lineY += 30; 
    } 
}//rect10x10 

所有工作正常(細線,以及間隔)第一次任一圖像被點擊時,問題是,當任一繪製矩形,下一個向上的作用。例如: 1)當首先調用1x10,然後再調用10x10時,最後一條垂直線變粗。 2)當10x10首先被調用,然後1x10時,最後的水平線根本不會被擦除。如果我再次調用1x10,現在最後的水平線會被擦除,但最後一條垂直線會變得更厚。

所有這些只是一個圖形參考,所以我可以很容易地顯示一個正方形的圖像分爲1x10或10x10和問題解決。不過,我真的很想知道我做錯了什麼,以備將來參考。 在此先感謝您的支持。

回答

0

當您的矩形爲stroke時,您將獲得其中一條路徑的剩餘部分。在致電rect之前致電ctx.beginPath();

,或者,跳過所有和使用strokeRect

ctx.beginPath(); 
ctx.rect(240, 390, 300, 300); 
ctx.lineWidth = 2; 
ctx.stroke(); 
ctx.lineWidth = 1; 

ctx.clearRect(200, 375, 355, 325); 
ctx.lineWidth = 2;  
ctx.strokeRect(240, 390, 300, 300); 
ctx.lineWidth = 1; 
+0

謝謝!由於我需要矩形具有白色背景,因此在rect之前放置ctx.beginPath()。所有的工作如預期的那樣。 –