为什么当我按下键时我的矩形不会移动?

Why won't my rectangle move when I press the key?

所以我正在尝试从头开始制作贪吃蛇游戏,作为在 javascript 中制作游戏的练习。我已经在我的 canvas 中制作了正方形,现在我正试图让它移动。这是我为它制作的代码。

     <!DOCTYPE html>
<html>
<body>

<canvas id = "gameCanvas" width="700" height="600" style="border:4px solid black; background-color: yellow"></canvas>

<script type = "text/javascript">
var myCanvas = document.getElementById("gameCanvas");
var ctx = myCanvas.getContext("2d");


    this.x = 0;
    this.y = 0;

    var snake = ctx.fillRect(this.x,this.y,10,10);

    myMovement = function(){
        var moveUp = event.keyCode;
        if(moveUp == 39){
            snake = ctx.fillRect(this.x + 1, this.y,10,10);
        }
    }

</script>
</body>
</html>

不幸的是,当我按下按钮时,没有任何反应。我的代码有什么问题。

问题发现:

  myMovement = function(){
        var moveUp = event.keyCode;
        if(moveUp == 39){
            snake = ctx.fillRect(this.x + 1, this.y,10,10);
        }
    }

myMovement 将触发时它不知道代码,并且

//x value just add 1 with previous but not increment gradually, so it should be this.x += 1    
ctx.fillRect(this.x + 1, this.y,10,10); 

解决方案:

  window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 39) {
    snake = ctx.fillRect(this.x += 1, this.y,10,10);
   }
}

您可以看到 here 的键盘键值

The onkeyup event occurs when the user releases a key (on the keyboard).

实际上有 3 种不同的选项可以触发按键事件

onkeydown

按键

onkeyup

您的代码存在一些问题。

  1. 您在要引用全局对象的地方使用 this(在本例中为 window)。
  2. 您的 myMovement 函数没有附加到任何东西,这意味着它没有设置为事件侦听器,当按下某个键时需要调用它
  3. 即使您的 myMovement 已设置,它也没有将 event 对象定义为参数,因此您的函数会出错,因为没有 event 对象可供访问

对于 1 如果你想跟踪 x,y 你可以将它们放在一个对象中并从那里访问它们:

var rect={
  x:0,
  y:0
};
//then when needing to use them access them like rect.x, rect.y
//also fillRect doesn't return anything so no need for "var snake = "
ctx.fillRect(rect.x, rect.y, 10, 10);

对于 23,您可以为您的函数使用各种键*事件。您可以使用 addEventListener 附加函数。最后为您的函数定义一个 event 参数,以便您实际上有一个要使用的事件对象:

function myMovement(event) {
    var moveUp = event.keyCode;
    if(moveUp == 39){
        //++rect.x adds one and assigns the new value to rect.x
        //and again fillRect doesn't return a value so no need for "snake ="
        ctx.fillRect(++rect.x, rect.y,10,10);
    }
}
window.addEventListner("keydown",myMovement);

演示

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

var rect = {
  x: 0,
  y: 0
};

ctx.fillRect(rect.x, rect.y, 10, 10);

window.onkeydown = function(event) {
  var moveUp = event.keyCode;
  if (moveUp == 39) {
    //erase last fill
    ctx.clearRect(rect.x, rect.y, 10, 10);
    ctx.fillRect(++rect.x, rect.y, 10, 10);
  }
}
<canvas id="gameCanvas" width="100%" height="100%" style="border:4px solid black; background-color: yellow"></canvas>