admin管理员组

文章数量:1290997

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 es 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>

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 es 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>
Share Improve this question edited Feb 2, 2016 at 23:19 josliber 44.3k12 gold badges102 silver badges135 bronze badges asked Jan 22, 2016 at 6:19 user1049876user1049876 1172 gold badges3 silver badges18 bronze badges 5
  • 1 Where is canvas1 defined ? – Rayon Commented Jan 22, 2016 at 6:22
  • When your script runs, your HTML isn't in DOM yet. Write the script after your HTML – Sandeep Nayak 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. – sdc 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. – zero298 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. – josliber Commented Feb 2, 2016 at 23:21
Add a ment  | 

4 Answers 4

Reset to default 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();
  }

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;

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

should be:

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

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.

本文标签: htmlUncaught TypeError Cannot read property 39width39 of undefined in JavaScriptStack Overflow