gpt4 book ai didi

javascript - HTML 文件不会在浏览器中显示任何内容

转载 作者:行者123 更新时间:2023-11-30 13:47:03 25 4
gpt4 key购买 nike

我一直在尝试通过编写一个简单的 2D 俄罗斯方 block 游戏来练习 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);

最佳答案

您的代码有错误:

  1. context.fillRect.getContext() 不正确。应该是 context.fillRect()
  2. 您的 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/

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