gpt4 book ai didi

javascript - 尽管数组值不同,仍绘制相同的矩形

转载 作者:行者123 更新时间:2023-11-28 05:35:42 25 4
gpt4 key购买 nike

我有一个图 block 数组,如下所示:

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

以及一个从该 map 将图 block 绘制到 Canvas 的循环

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”都按预期显示为黑色方 block 。问题是,尽管 if 语句的 fillStyle 中声明了不同的颜色,但每个“2”和“3”也显示为黑色方 block 。

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

最佳答案

您可以使用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>

关于javascript - 尽管数组值不同,仍绘制相同的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39378850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com