title: Moving a sprite image using arrow keys in JavaScript
body: <p>I have to animate a robo such that it would move around an HTML5 Canvas.
  Here's my image: <a href="https://i.stack.imgur.com/oecS2.png" rel="nofollow noreferrer">https://i.stack.imgur.com/oecS2.png</a></p>
  <p>The instructions I have to work on my animation are:</p>
  <ol>
  <li>If you are not pressing a button, the skeleton should not move and should just be facing you.</li>
  <li>If you press the right arrow key or “d” then it should move to the right.</li>
  <li>If you press the left arrow key or “a” then it should move to the left.</li>
  <li>If you press the up arrow key or “w” then it should move up.</li>
  <li>If you press the down arrow key or “s” then it should move down</li>
  <li>If it gets to the edge of the canvas, it should keep walking but not move</li>
  </ol>
  <p>I haven't been able to find any helpful resources that would guide me to move my sprite image using arrow keys. And I know a bit of making an image move using mouse but not using arrow keys. But here's what I've tried so far.</p>
  <p><strong>JavaScript:</strong></p>
  <pre><code>var tID;
  
  function stopAnimate()
  {
      clearInterval(tID);
  }
  
  function animateScript()
  {
      var position = 256;
      const diff = 256;
  
      tID = setInterval ( () =&gt; {
          document.getElementById(&quot;image&quot;).style.backgroundPosition = `-${position}px 0px`;
  
          if (position &lt; 1536)
          {
              position = position + diff;
          }
          else
          {
              position = 256;
          }
      }, 100);
  }
  </code></pre>
  <p><strong>HTML:</strong></p>
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;link rel='stylesheet' type='text/css' href='Robot.css'&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;h2&gt;Animation&lt;/h2&gt;
  
          &lt;div id =&quot;demo&quot;&gt;
              &lt;p id=&quot;image&quot; onmouseover=&quot;animateScript()&quot; onmouseout=&quot;stopAnimate()&quot;&gt;&lt;/p&gt;
          &lt;/div&gt;
  
          &lt;script src=&quot;Animate.js&quot;&gt;&lt;/script&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  <p><strong>CSS:</strong></p>
  <pre><code>body
  {
      background: white;
      color: black;
  }
  
  #image
  {
      height: 256px;
      width:  256px;
      background: url('robo.png') 0px 0px;
  }
  </code></pre>
  <p>The code above isn't the right thing that I need but I was just testing it using my knowledge about moving sprites using a mouse but I need some help on rotating my image using arrow keys. Any help would be appreciated!</p>