title: Smooth keydown animation on Canvas in JavaScript
body: <p>I'm very new to programming and I'm trying to create some code that will allow me to move a square around the Canvas by pressing arrow keys. I'm able to get the square to move, but its motion isn't very smooth. I have it moving by increments of 10 pixels at a time, so I understand why it feels kind of jerky, because there isn't any animation between each position of 10-frames-difference, but having it move by smaller increments makes it far too slow. What I've done so far is below:</p>
  
  <pre><code>window.onload = function init() {
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      setInterval(gameLoop,50);
      window.addEventListener('keydown',whatKey,true);
  }
  
  avatarX = 400
  avatarY = 300
  
  function gameLoop() {
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      canvas.width = 800
      canvas.height = 600
      ctx.fillRect(avatarX,avatarY,50,50);
  }
  
  function whatKey(e) {
      switch(e.keyCode) {
      case 37:
          avatarX = avatarX - 10;
          break;
      case 39:
          avatarX = avatarX + 10;
          break;
      case 40:
          avatarY = avatarY + 10;
          break;
      case 38:
          avatarY = avatarY - 10;
          break;
      }
  }
  </code></pre>
  
  <p>Every time I press the arrow key right, I would like for the square to move smoothly in that direction at a constant rate. Thanks in advance for any help at all!</p>