2016-09-07 77 views
1

得出相同的矩形我有一個小塊陣列,它看起來像這樣:儘管不同的陣列價值

var gameCanvas = document.getElementById('canvas'); 
var ctx = gameCanvas.getContext("2d"); 

var mapArray = [ 
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
[1,1,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0], 
[1,1,1,1,0,0,0,0,0,0,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0], 
[1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,3,0,0,0] 
]; 

以及能夠吸引瓷磚到畫布上從地圖

var posX = 0; 
var posY = 0; 

for(i=0; i < mapArray.length; i++){ 
    for(j=0; j < mapArray[i].length; j++){ 
     if(mapArray[i][j] == 1){ 
      ctx.rect(posX, posY, 32, 32); 
      ctx.fillStyle="black"; 
     } 
     if(mapArray[i][j] == 2){ 
      ctx.rect(posX, posY, 32, 32); 
      ctx.fillStyle="red"; 
     } 
     if(mapArray[i][j] == 3){ 
      ctx.rect(posX, posY, 32, 32); 
      ctx.fillStyle="blue"; 
     } 
     ctx.fill(); 
     posX += 32;  
    } 
    posX = 0; 
    posY +=32; 
} 

每一個「1」的循環在陣列中顯示爲一個黑色的正方形。 問題是,儘管在if語句的fillStyle中聲明瞭不同的顏色,但「2」和「3」也顯示爲黑色方塊。

記錄時,每個if語句按預期返回值(1,2或3)。

回答

0

您可以使用ctx.beginPath()ctx.stroke()作爲嵌套命令。

var gameCanvas = document.getElementById('canvas'), 
 
    ctx = gameCanvas.getContext("2d"), 
 
    mapArray = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,0,0,1,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0],[1,1,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,3,0,0,0]], 
 
    posX = 0, 
 
    posY = 0, 
 
    i, j; 
 

 
for (i = 0; i < mapArray.length; i++){ 
 
    posX = 0; 
 
    for (j = 0; j < mapArray[i].length; j++) { 
 
     if (mapArray[i][j]) { 
 
      ctx.beginPath(); 
 
      ctx.rect(posX, posY, 32, 32); 
 
      ctx.fillStyle = ["black", "red", "blue"][mapArray[i][j] - 1]; 
 
      ctx.fill(); 
 
      ctx.stroke(); 
 
     } 
 
     posX += 32;  
 
    } 
 
    posY += 32; 
 
}
<canvas id="canvas" width="1000" height="1000"></canvas>

+1

因此,使用beginPath方法來單獨的rects,否則會被認爲是相同的形狀的一部分。很高興知道。謝謝,這很有幫助。 –