运动对象在画布上消失

我是javascript的新手,我正在尝试制作一个简单的游戏,其中的对象在屏幕上向左和向右移动。我试图使其与箭头键一起使用,但我的对象消失了,我不知道该怎么办。

确切的问题: 当我按向左或向右箭头时,该对象消失并且从不出现在屏幕上,直到我用chrome刷新页面。

var gameboard;
var ctx; 
var background;
var rocket;
var multiplier = 5;


window.addEventListener("keydown", (event) =>{
    switch (event.key) {
      case 'ArrowLeft' : rocket.x = `${parseInt(rocket.x) - multiplier}px`; break;
      case 'ArrowRight' : rocket.x = `${parseInt(rocket.x) + multiplier}px`; break;
    }
  });


class Background {
  constructor(x, y, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.width = gameboard.width;
    this.height = gameboard.height;
  }

  render() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}


class Rocket {

  constructor(x, y, width, height, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.color = color;
  }


  render() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}


function gameloop() {
    update();
    clearGameboard();
    render();
    requestAnimationFrame(gameloop);
}

function update() {
}

function clearGameboard() {
  ctx.clearRect(0, 0, gameboard.width, gameboard.height);
}

function render() {
  background.render();
  rocket.render();
} 



window.onload = function() {


  gameboard = document.getElementById("gameboard");

  ctx = gameboard.getContext('2d');

  background = new Background(0, 0, "navajowhite");

  rocket = new Rocket(25, 25, 100, 100, "black");


  gameloop();                     
}
<body>
  <canvas id="gameboard" width="600" height="600"></canvas>
</body>
评论