我一直在尝试通过编码一个简单的2D Tetris游戏来练习javascript,但是当我在尝试创建游戏空间之后在浏览器中查看它时,浏览器中没有任何显示,并且完全空白。我已经尝试了一切,但似乎无法正常工作,而且我不知道这是我的代码还是其他东西。任何帮助都非常感谢!

<!DOCTYPE html>
<html>
<head>
    <title>Tetris</title>
</head>
<body>
    <canvas id="tetris" width="240" height="400"></canvas>
    <script src="tetris.js"></script>
</body>
</html>


const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');

context.scale(20,20);

context.fillStyle = 'black';
context.fillRect.getContext(0, 0 , context.width, context.height);

const matrix = [
    [0, 0, 0],
    [1, 1, 1],
    [0, 1, 0]
];

function drawMatrix(){
    matrix.forEach((row, y) => {
        row.forEarch((value, x) => {
            if (value != 0) {
                context.fillStyle = 'red';
                context.fillRect(x, y, 1, 1);
            }
        });
    });
}

drawMatrix(matrix);

最佳答案

您的代码有错误:


context.fillRect.getContext()不正确。应该是context.fillRect()
您的forEach()循环有错字。您正在写forEarch()。应该是forEach()




const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');

context.scale(20, 20);

context.fillStyle = 'black';
context.fillRect(0, 0, context.width, context.height);

const matrix = [
  [0, 0, 0],
  [1, 1, 1],
  [0, 1, 0]
];

function drawMatrix() {
  matrix.forEach((row, y) => {
    row.forEach((value, x) => {
      if (value != 0) {
        context.fillStyle = 'red';
        context.fillRect(x, y, 1, 1);
      }
    });
  });
}

drawMatrix(matrix);

<!DOCTYPE html>
<html>

<head>
  <title>Tetris</title>
</head>

<body>
  <canvas id="tetris" width="240" height="400"></canvas>
  <script src="tetris.js"></script>
</body>

</html>

关于javascript - HTML文件不会在浏览器中显示任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59100664/

10-09 15:02