首页 > 解决方案 > 如何根据按下的键使图像移到一侧?

问题描述

我在画布上加载了一个图像,但是它已经复制了它并且有两个。并且图像也根本不会根据命令移动。请帮忙

   let img = document.getElementById("ship");
let player = {
  x: 375,
  y: 550,
  w: 50,
  h: 50,
};
requestAnimationFrame(draw);

function draw() {
  ctx.drawImage(img, 5, 5);
  ctx.img(player.x, player.y, player.w, player.h);
  //Draw

  //Request another frame
  requestAnimationFrame(draw);
}

document.addEventListener("keydown", move);

function move(event) {
  if (event.code == "ArrowRight") {
    player.x = player.x + 50;
  }
}

标签: javascriptcanvas

解决方案


您需要使用键码才能移动,它们在这里。

down arrow  37
up arrow    38
right arrow 39
down arrow  40

将您的代码更改为以下内容,它应该可以工作。

function move(event) {
  if (event.code === 39) {
    player.x = player.x + 50;
  }
}

不知道为什么你有两张图片,但以下几行会导致问题

  ctx.drawImage(img, 5, 5);
  ctx.img(player.x, player.y, player.w, player.h);

你只需要这个,

ctx.drawImage(img, player.x, player.y, player.w, player.h);

ctx.img也不是有效的上下文函数。

绘制图像文档


推荐阅读