title: How to move an object using arrow keys using javascript
body: <p>I want to be able to move a rectangle (that I created using javascript) around using the arrow keys. Also I want it to stop when hitting the end of my canvas. How do I do that? I'm all new at this and have absolutely no clue. </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function fillRect () {
  
  var canvas = document.getElementById("myCanvas"); 
  var context = canvas.getContext("2d");
  
  var rectX=10;
  var rectY=10;
  
  context.rect(rectX,rectY,50,50);         
  context.fillStyle = "#666666";
  context.fill();
  }
  
    function onkeydown(e) {
    if(e.keyCode==39) {rectX++;} //right arrow
    elseif(e.keyCode==37) {rectX--;} //left arrow
    elseif(e.keyCode==38) {rectY--;} //up arrow
    elseif(e.keyCode==40) {rectY++;} //down arrow
    fillRect();
  }
  window.addEventListener("keydown", onkeydown);</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>#myCanvas {
  margin: auto;
  display: block;
  width: 80%;
  height: 400px;
  background-color: white;
  border: 3px solid black;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Jessica Odefjord --&gt;
  &lt;!DOCTYPE HTML&gt; 
   &lt;html lang="sv"&gt;
    &lt;head&gt;
     &lt;meta charset="utf-8"&gt;
     &lt;link rel="stylesheet" type="text/css" href="inlämningsuppgift_javascript_jessicaodefjord.css" /&gt;
     &lt;script type="text/javascript" src="inlämningsuppgift_javascript_jessicaodefjord.js"&gt;&lt;/script&gt;
     &lt;title&gt;Flytta rektangeln&lt;/title&gt;
    &lt;/head&gt;
     &lt;body&gt;
      &lt;header&gt;
       &lt;h1&gt;Flytta rektangeln&lt;/h1&gt;
       &lt;h2&gt;Flytta runt rektangeln med hjälp av piltangenterna&lt;/h2&gt;
      &lt;/header&gt;
       &lt;main&gt;
        &lt;section id="firstsection"&gt;
         &lt;h3&gt;
         &lt;/h3&gt;
        &lt;/section&gt;
         &lt;canvas id="myCanvas"&gt;
         &lt;/canvas&gt;
       &lt;/main&gt;
     &lt;/body&gt;
   &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>