Search code examples
javascripthtmlcsskeyboard-events

Why does my Javascript canvas not move on keyboard input?


So recently I got into Javascript and I watched some few tutorials and read a StackOverflow Question asking a simular thing.

For some reason my Canvas Object wont move and I did seemingly everything like many other examples.

My Code:

  document.addEventListener('keydown', function(event){
    switch (event.keyCode) {
      case 87:
      alert("w");
        break;
      case 65:
      alert("a");
        break;
      case 83:
      alert("s");
        break;
      case 68:
      moveRight();
        break;
      case 38:
      alert("up");
          break;
      case 37:
      alert("right");
        break;
      case 39:
      alert("left");
        break;
      case 40:
      alert("down");
        break;
  }
})

function moveRight() {
  var element = document.getElementById("plr");
  element.style.left = parseInt(element.style.left) - 5 + 'px';
}

// w = 87
// a = 65
// s = 83
// d = 68
// up = 38
// right = 37
// left = 39
// down = 40
#bg{
  background-color: blue;
  height: 700px;
  width: 1200px;
  position: relative;
  left: -10px;
  top: -10px;
}
#plr{
  background-color: red;
  height: 50px;
  width: 50px;
  position: absolute;
  left: 50px;
  top: 300px;
}
<!DOCTYPE html>
<html lang="de" dir="ltr">
  <head>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
    <meta charset="utf-8">
    <title></title>
  </head>
  <body onload="">
    <canvas id="bg"></canvas>
    <canvas id="plr"></canvas>
  </body>
</html>

I know that Im making a dumb/small mistake somewhere but I cannot find it. Thanks for any kind of help.


Solution

  • The following fixes your problem...

      <canvas id="plr" style="left: 50px;top: 300px;"></canvas>
    

    The reason why it doesn't work the way you've done it is because you haven't initialised style.left;

    Setting left in css doesn't put that value in style.left

    The following doesn't work which is what you are doing:

    console.log("left=" + document.getElementById("player").style.left);
    #player {left:100px}
    <canvas id="player">

    Console will just print "left=" and no value.

    So, when you do the following

    element.style.left = parseInt(element.style.left) - 5 + 'px';
    

    What you end up doing is parseInt("") - 5 + 'px' which gives you "NaNpx" and therefore doesn't move.

    You can initialise style.left by applying it to the canvas directly as shown below:

    console.log("left=" + document.getElementById("player").style.left);
    <canvas id="player" style="left:100px">

    The console output will become left=100px

    Which means your existing moving player code will now work.

    If prefer not to set left style within the HTML then alternative is to use element.getBoundingClientRect(); and calculate left from that

    See: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect