尽管数组值不同,但绘制了相同的矩

时间:2016-09-07 20:55:16

标签: javascript arrays html5-canvas

我有一个看起来像这样的磁贴阵列:

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;  
}

每一个&#39; 1&#39;在数组中显示为预期的黑色方块。 问题是,每一个&#39; 2&#39;和&#39; 3&#39;尽管在if语句的fillStyle中声明了不同的颜色,但也显示为黑色方块。

记录时,每个if语句按预期返回值(1,2或3)。

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
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;
}
&#13;
<canvas id="canvas" width="1000" height="1000"></canvas>
&#13;
&#13;
&#13;