3

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:

    var cw=canvas.width;

I have been trying to use this code on Chrome. Here is the full code:

<html>
        <head>
            <script>
            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();
            }
            </script>
        </head>
        <body>
            <div id="firstDiv">
                <canvas id="canvas1" width="500" height="500" style="border: 1px solid black;"> </canvas>

            </div> 
        </body> 
    </html>
5
  • 1
    Where is canvas1 defined ? Commented Jan 22, 2016 at 6:22
  • When your script runs, your HTML isn't in DOM yet. Write the script after your HTML Commented Jan 22, 2016 at 6:23
  • @user1049876 you really shouldn't edit the title of the question, except to make it more clear. If others want to reference this example they won't search for Resolved ERROR: SOLVED It's best to keep the original question, or clarify what the problem was. Commented Jan 23, 2016 at 20:13
  • Stop deleting all of the content out of your questions. You are doing a disservice to your question and to the people that are helping you by removing all of the pertinent information from you question. You did it in this question, and you did it in you near identical other question. Commented Jan 25, 2016 at 23:04
  • Please stop removing part or all of your question after they have been solved -- if the code is removed then the question will no longer be helpful to future visitors. Commented Feb 2, 2016 at 23:21

4 Answers 4

3

Here is a working live demo

You should use the window.onload function to make sure the HTML gets loaded before trying to access any DOM objects. This syntactically decouples your JavaScript from the HTML.

  var positionX = 0;
  var positionY = 0;
  var canvas = {};
  var cw = 0;
  var ch = 0;
  var bw = 100;
  var bh = 100;

 // Set up initial values, after the page loads 
 window.onload = function(){
     positionX = 0;
     positionY = 0;
     canvas = document.getElementById("canvas");
     cw = canvas.width;
     ch = canvas.height;
     draw();
  };
  // Add keyboard listener
  window.addEventListener("keydown", onKeyPress, true);

  function draw(){
      canvas=document.getElementById("canvas");
      cw=canvas.width;
      ch=canvas.height;
      context=canvas.getContext("2d");

      context.clearRect(0, 0, canvas.width, canvas.height);
      context.fillStyle="green";

      context.fillRect(positionX, positionY, bw, bh);
      context.strokeStyle = 'black';
      context.stroke();
  }

  function onKeyPress(e){
    var dx = 50;
    var dy = 15;
    if (e.keyCode == 87){
        console.log("w(87) up");
        positionY=Math.max(0,positionY-dy);
    }
    else if (e.keyCode == 83){
        console.log("s(83) down");
        positionY = Math.min((positionY+dy), (ch-bh));
    }
    else if (e.keyCode == 68){
        console.log("d(68) right");
        positionX = Math.min((positionX+dx), (cw-bw));
    }
    else if (e.keyCode == 65){
        console.log("a(65) left");
        positionX=Math.max(0,positionX-dx);
    }
    draw();
  }
Sign up to request clarification or add additional context in comments.

Comments

1

Some problems are here

        var positionY=0;
        var cw=canvas.width;
        var ch=canvas.height;

Here canvas variable is undefined . You trying to access canvas before settings its value.

var canvas=document.getElementById("canvas");
var cw=canvas.width;
var ch=canvas.height;

and

            var canvas=document.getElementById("canvas1");
            var cw=canvas1.width;
            var ch=canvas1.height;

there is no variable canvas1 so this should be

            var canvas1=document.getElementById("canvas1");
            var cw=canvas1.width;
            var ch=canvas1.height;

Comments

0

var canvas=document.getElementById("canvas1");

should be:

var canvas1=document.getElementById("canvas1");

Comments

0

A quick fix:

</head>
<body>
    <div id="firstDiv">
        <canvas id="canvas" width="500" height="500" style="border: 1px solid black;"> </canvas>

    </div>
    <script>
      var positionX=0;
      var positionY=0;
      var canvas=document.getElementById("canvas");
      var cw=canvas.width;
      var ch=canvas.height;


      window.addEventListener("keydown", onKeyPress, true);

      function draw(){
          var canvas=document.getElementById("canvas");
          var cw=canvas.width;
          var ch=canvas.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();
      }
    </script>
</body>

Your script related to the canvas dom should not run before the canvas rendered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.