title: Uncaught TypeError: Cannot read property 'width' of undefined in JavaScript
body: <p>I have created a program that can move a rectangular block up, down, right, and left within a canvas using the w, a, s, and d keys. There is an error when setting a variable to represent the width of the canvas. The error comes up for this line of code:</p>
  
  <pre><code>    var cw=canvas.width;
  </code></pre>
  
  <p>I have been trying to use this code on Chrome. Here is the full code:    </p>
  
  <pre><code>&lt;html&gt;
          &lt;head&gt;
              &lt;script&gt;
              var positionX=0;
              var positionY=0;
              var cw=canvas.width;
              var ch=canvas.height;
  
              var canvas=document.getElementById("canvas1");
  
              window.addEventListener("keydown", onKeyPress, true);
  
              function draw(){
                  var canvas=document.getElementById("canvas1");
                  var cw=canvas1.width;
                  var ch=canvas1.height;
                  var context=canvas.getContext("2d");
                  context.clearRect(0, 0, canvas.width, canvas.height);
  
                  context.fillStyle="green";
                  context.fillRect(positionX, positionY, 100, 100);
                  context.strokeStyle = 'black';
                  context.stroke();
              }
  
          function onKeyPress(e){
              if (e.keyCode==87){
                  positionY=Math.max(0,positionY-15);
              }
              if (e.keyCode==83){
                  positionY=Math.min(cw-500,positionY+15);
              }
              if (e.keyCode==68){
                  positionX=Math.min(ch-500,positionX+50);
              }
              if (e.keyCode==65){
                  positionX=Math.max(0,positionX-50);
              }
          draw();
              }
              &lt;/script&gt;
          &lt;/head&gt;
          &lt;body&gt;
              &lt;div id="firstDiv"&gt;
                  &lt;canvas id="canvas1" width="500" height="500" style="border: 1px solid black;"&gt; &lt;/canvas&gt;
  
              &lt;/div&gt; 
          &lt;/body&gt; 
      &lt;/html&gt;
  </code></pre>