我试图复制并从这个教程中学习:https: //www.youtube.com/watch? v=txUvD5_ROIU但我想将内联 javascript 移动到 Visual Studio Code 中的单独 .js 文件中。这使得代码运行不正确,我无法为我的生活找出原因。我试图以不同的方式构造它,但我不熟悉 javascript 以找出问题所在。这是代码:
HTML:
<!DOCTYPE html>
<canvas id="game" width="400" height="400"></canvas>
<script src="script.js" type="text/javascript" >
</script>
Javascript:
var ctx = null;
var tileW = 40;
var tileH = 40;
var mapW = 10;
var mapH = 10;
var currentSecond = 0, frameCount = 0, framesLastSecond = 0;
var gameMap = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 0, 1, 1, 1, 1, 0,
0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 0,
0, 1, 0, 1, 0, 0, 0, 1, 1, 0,
0, 1, 0, 1, 0, 1, 0, 0, 1, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 0,
0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
0, 1, 1, 1, 0, 1, 1, 1, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];
window.onload = function () {
ctx = document.getElementById('game').getContext('2d');
requestAnimationFrame(drawGame);
ctx.font = "bold 10pt sans-serif";
}
function drawGame() {
if (ctx == null) { return; }
var sec = Math.floor(Date.now() / 1000);
if (sec != currentSecond) {
currentSecond = sec;
framesLastSecond = frameCount;
frameCount = 1;
} else { frameCount = frameCount + 1; }
for (var y = 0; x < mapH; y++) {
for (var x = 0; x < mapW; x++) {
switch(gameMap[((y*mapW)+x)])
{
case 0:
ctx.fillStyle = "#000000";
break;
default:
ctx.fillStyle = "#ccffcc";
}
ctx.fillRect( x*tileW, y*tileH, tileW, tileH);
}
}
ctx.fillStyle = "#ff0000";
ctx.fillText("FPS: " + frameCount, 10, 20);
requestAnimationFrame(drawGame);
}
任何帮助是极大的赞赏!