fillrect 在 javascript for 循环中不起作用

fillrect not working in javascript for loop

我正在尝试使用 for 循环为俄罗斯方块游戏绘制棋子。我找不到一个单独的教程或解释,以我使用它的方式使用带有 fillrect 和 fill 样式的循环。我知道如何让它与 foreach 一起工作,但由于某些原因它不能在 for 循环中工作。

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

const T = {
    "first": [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 1, 1, 1, 0],
        [0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0]
    ],

    "second": [
        [0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0],
        [0, 1, 1, 0, 0],
        [0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0]
    ],

    "third": [
        [0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0],
        [0, 1, 1, 1, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]
    ],

    "forth": [
        [0, 0, 0, 0, 0],
        [0, 0, 1, 0, 0],
        [0, 0, 1, 1, 0],
        [0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0]
    ],
}

var peice = T.first

function colorPeice(peice) {
    for(i = 0; i < peice.length; i++) {
        for(j = 0; j < peice.length; j++) {
            if (peice[i][j] !== 0) {
                ctx.fillstyle = 'red';
                ctx.fillRect(0, 0, 1, 1); 
            }
        }
    }
}

function drawCanvas() {
    ctx.fillStyle = "black";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    colorPeice(peice);
} 

drawCanvas();

我知道在 运行 时会看到这些值,但它们没有填充。

我试过了

function colorPeice(peice) {
    for(i = 0; i < peice.length; i++) {
        for(j = 0; j < peice.length; j++) {
            if (peice[i][j] !== 0) {
                ctx.fillstyle = 'red';
                ctx.fillRect(j, i, 1, 1); 
            }
        }
    }
}

而且它不起作用。我做错了什么??

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

function colorPeice(peice) {
    for(i = 0; i < peice.length; i++) {
        for(j = 0; j < peice[i].length; j++) {
            if (peice[i][j] !== 0) {
                ctx.fillStyle = 'red';
                ctx.fillRect(j*10, i*10, 10, 10); 
                console.log('fill', i*10, j*10)   
            }
        }
    }
    ctx.fill();
}
piece = [[1,1,1,1,1],[2,2]]
colorPeice(piece)
<canvas id="canvas" height="500px", width="500px">

</canvas>

尝试此代码(并查看我对您的 post 的评论)。

function colorPeice(peice) {
    for(i = 0; i < peice.length; i++) {
        for(j = 0; j < peice.length; j++) {
            if (peice[i][j] !== 0) {
                ctx.fillStyle = 'red';
                ctx.fillRect(j*10, i*10, 10, 10); 
            }
        }
    }
}