How do I make an image move to the side, depending on which key has been pressed?

Viewed 18

I have an image loaded on the canvas, however it has made a duplicate of it and there are two. And the image does not move at all on command either. Please help

   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;
  }
}
1 Answers

You need to use the keycodes in order to move, here they are.

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

Change your code to the following and it should work.

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

Not sure why you have two images but the following lines will cause an issue

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

You only need this,

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

ctx.img isn't a valid context function either.

drawImage docs

Related