admin管理员组

文章数量:1294322

I've tried everything to solve this problem and nothings working. Posting here is my last resort.

I'm trying to code a simple canvas element and load everything dynamically and nothing is working. I keep getting the error in Google console "Uncaught ReferenceError: ctx is not defined" on game.js:33.

I originally thought it was because mon.js is being loaded after the other 2 javascript files so I made a loader file which loads each JS file in the order I want. I did this using $.getScript() and the $.when() function . Unfortunately, this did not work. So the ctx var is being loaded but it's giving me the error for some reason.

I've included the files below. Thanks in advance for any help.

EDIT: I just tried taking all the code out of each individual JS file and putting them in the same one in the order they are meant to be in and it works fine now. But it would be nice to know why it was not working at all. As it's going to get very hectic having all my code in 1 file. Thank you.

index.php

<!doctype>
<html>
<head>
   <title>Game - Unknown</title>
   <link rel="stylesheet" href="./assets/css/default.css">
   <script src=".9.1.min.js"></script>
   <script src=".3.3.min.js"></script>
   <!--<script src="./assets/js/loader.js"></script>-->
   <script src="./assets/js/mon.js"></script>
   <script src="./assets/js/graphics.js"></script>
   <script src="./assets/js/game.js"></script>
</head>
<body>
<canvas id="viewport"></canvas>
</body>
</html>

mon.js

   $(document).ready(function(){

      // Setup the canvas game context for 2D
      var canvas = document.getElementById("viewport");
      var ctx = canvas.getContext("2d");

      // Update the canvas dimensions to match window size when changed
      $(window).resize(function(){canvasResize()}); canvasResize();

      function canvasResize(){
         var cWidth = window.innerWidth;
         var cHeight = window.innerHeight;

         canvas.width = cWidth;
         canvas.height = cHeight;

         ctx.clearRect(0, 0, canvas.width, canvas.height);
         ctx.fillStyle = '#000';
         ctx.fillRect(0, 0, cWidth, cHeight);
      }

      // Get center of things - Useful for centering images on canvas
      function getCenter(dim){ return dim / 2 }

   });

graphics.js

   $(document).ready(function(){

      function gfxTile(x, y, w, h, r, g, b, a)
      {
         ctx.fillStyle = "rgb(60, 60, 100)";
         ctx.beginPath();
         //ctx.moveTo(x + h / 2, y + w / 2);
         ctx.moveTo(10, 10);
         ctx.lineTo(105, 25);
         ctx.lineTo(25, 105);
         ctx.lineTo(25, 105);
         ctx.closePath();
         ctx.fill();
      }

   });

game.js

   $(document).ready(function(){

      // START TEMPORARY
      var mapSizeX = 10;
      var mapSizeY = 10;
      var mapArray = new Array();

      function createMap()
      {
         for(x = 0; x < mapSizeX; x++)
         {
            mapArray[x] = [];

            for(y = 0; y < mapSizeY; y++)
            {
               mapArray[x][y] = 0;
            }
         }
      }
      // END TEMPORARY

      setInterval(mainLoop, 50);

      function mainLoop()
      {
         //gfxTile(10, 10, 40, 40, 50, 50, 50, 100);
         ctx.clearRect(0, 0, canvas.width, canvas.height);
      }

   });

I've tried everything to solve this problem and nothings working. Posting here is my last resort.

I'm trying to code a simple canvas element and load everything dynamically and nothing is working. I keep getting the error in Google console "Uncaught ReferenceError: ctx is not defined" on game.js:33.

I originally thought it was because mon.js is being loaded after the other 2 javascript files so I made a loader file which loads each JS file in the order I want. I did this using $.getScript() and the $.when() function . Unfortunately, this did not work. So the ctx var is being loaded but it's giving me the error for some reason.

I've included the files below. Thanks in advance for any help.

EDIT: I just tried taking all the code out of each individual JS file and putting them in the same one in the order they are meant to be in and it works fine now. But it would be nice to know why it was not working at all. As it's going to get very hectic having all my code in 1 file. Thank you.

index.php

<!doctype>
<html>
<head>
   <title>Game - Unknown</title>
   <link rel="stylesheet" href="./assets/css/default.css">
   <script src="http://code.jquery./jquery-1.9.1.min.js"></script>
   <script src="http://d3lp1msu2r81bx.cloudfront/kjs/js/lib/kinetic-v4.3.3.min.js"></script>
   <!--<script src="./assets/js/loader.js"></script>-->
   <script src="./assets/js/mon.js"></script>
   <script src="./assets/js/graphics.js"></script>
   <script src="./assets/js/game.js"></script>
</head>
<body>
<canvas id="viewport"></canvas>
</body>
</html>

mon.js

   $(document).ready(function(){

      // Setup the canvas game context for 2D
      var canvas = document.getElementById("viewport");
      var ctx = canvas.getContext("2d");

      // Update the canvas dimensions to match window size when changed
      $(window).resize(function(){canvasResize()}); canvasResize();

      function canvasResize(){
         var cWidth = window.innerWidth;
         var cHeight = window.innerHeight;

         canvas.width = cWidth;
         canvas.height = cHeight;

         ctx.clearRect(0, 0, canvas.width, canvas.height);
         ctx.fillStyle = '#000';
         ctx.fillRect(0, 0, cWidth, cHeight);
      }

      // Get center of things - Useful for centering images on canvas
      function getCenter(dim){ return dim / 2 }

   });

graphics.js

   $(document).ready(function(){

      function gfxTile(x, y, w, h, r, g, b, a)
      {
         ctx.fillStyle = "rgb(60, 60, 100)";
         ctx.beginPath();
         //ctx.moveTo(x + h / 2, y + w / 2);
         ctx.moveTo(10, 10);
         ctx.lineTo(105, 25);
         ctx.lineTo(25, 105);
         ctx.lineTo(25, 105);
         ctx.closePath();
         ctx.fill();
      }

   });

game.js

   $(document).ready(function(){

      // START TEMPORARY
      var mapSizeX = 10;
      var mapSizeY = 10;
      var mapArray = new Array();

      function createMap()
      {
         for(x = 0; x < mapSizeX; x++)
         {
            mapArray[x] = [];

            for(y = 0; y < mapSizeY; y++)
            {
               mapArray[x][y] = 0;
            }
         }
      }
      // END TEMPORARY

      setInterval(mainLoop, 50);

      function mainLoop()
      {
         //gfxTile(10, 10, 40, 40, 50, 50, 50, 100);
         ctx.clearRect(0, 0, canvas.width, canvas.height);
      }

   });
Share edited Mar 24, 2013 at 21:06 Brad Bird asked Mar 24, 2013 at 21:01 Brad BirdBrad Bird 7371 gold badge12 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

var ctx = canvas.getContext("2d"); created a variable called ctx in the scope of the function you passed into $(document).ready();

When the function inside of game.js executes, there is no ctx variable in its scope, or the parent scope, window.

An easy fix would be changing

var ctx = canvas.getContext("2d");

to

window.ctx = canvas.getContext("2d");

Your ctx variable is already on a reachable namespace, your problem is basically a result of loading files with no order and priority. You can however use a script loader to solve the problem and make sure your variable is already defined before using it.

In this example I'm using the head.js script loader.

<script src="js/head.js"></script>
<script>
head.js(
"http://code.jquery./jquery-1.9.1.min.js",
    "http://d3lp1msu2r81bx.cloudfront/kjs/js/lib/kinetic-v4.3.3.min.js", 
    "js/mon.js", 
    "js/graphics.js", 
    "js/game.js"
); 

You can optimize your code even more using requireJS to expose only the namespaces you want . Check them out.

本文标签: javascriptUncaught ReferenceError ctx is not definedStack Overflow