我的 Javascript 程序在拾取箭头键时除了 console.log() 之外什么都不执行

My Javascript program won't execute anything but console.log() when it comes to picking up arrow keys

所以这是我的代码:

   document.onkeydown = checkKey;

function checkKey(e) {

  e = e || window.event;

if (e.keyCode == '38') {
}
    else if (e.keyCode == '40') {
        console.log("Down Arrow");
        g.rect( 200,200,20,20); << Here is the problem. This is ignored.
    }
    else if (e.keyCode == '37') {
        // left arrow
    }
    else if (e.keyCode == '39') {
        // right arrow
    }
}
rect( snake.X,snake.Y,20,20 );

我希望代码更改块在 canvas 上的位置,但是当我按下它时所有向下箭头都在控制台中写入,"Down Arrow." 它不会显示X 处的矩形:200 Y:200。有人可以帮忙吗?我这样做是为了玩蛇游戏。

您需要告诉您的程序绘制您使用命令 ctx.stroke(); 指定的矩形。下面的代码片段中显示了一个示例,您需要单击 iframe,然后按向下箭头进行注册。

如果这不起作用,请告诉我。

document.onkeydown = checkKey;

function checkKey(e) {

  e = e || window.event;
  
  var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

if (e.keyCode == '38') {
}
    else if (e.keyCode == '40') {
        console.log("Down Arrow");
        ctx.rect( 10,10,20,20); 
        ctx.stroke();
    }
    else if (e.keyCode == '37') {
        // left arrow
    }
    else if (e.keyCode == '39') {
        // right arrow
    }
}
.box {
  height: 100px;
  width: 100px;
  border: 1px solid black;
  }
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>