我试过一切解决这个问题和nothings工作。在这里发帖是我的最后一招。未捕获ReferenceError:ctx未定义
我想编码一个简单的画布元素和动态加载一切,没有任何工作。在game.js:33上,我一直在Google控制台中发现错误“Uncaught ReferenceError:ctx is not defined”。
我原本以为是因为common.js被加载后的其他2个JavaScript文件,所以我做了一个加载器文件加载每个JS文件以我想要的顺序。我用$ .getScript()和$ .when()函数做了这个。不幸的是,这不起作用。所以ctx var被加载,但由于某种原因,它给了我错误。
我已经包含下面的文件。预先感谢您的帮助。
编辑:我只是试图从每个单独的JS文件中取出所有的代码,并将它们放入相同的顺序,他们的意图是在现在,它现在正常工作。但很高兴知道为什么它根本不起作用。因为它将变得非常忙碌,我的所有代码都放在1个文件中。谢谢。
的index.php
<!doctype>
<html>
<head>
<title>Game - Unknown</title>
<link rel="stylesheet" href="./assets/css/default.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.3.min.js"></script>
<!--<script src="./assets/js/loader.js"></script>-->
<script src="./assets/js/common.js"></script>
<script src="./assets/js/graphics.js"></script>
<script src="./assets/js/game.js"></script>
</head>
<body>
<canvas id="viewport"></canvas>
</body>
</html>
common.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);
}
});
哦,我明白了!我不知道$(document).ready()有一个局部范围,并且认为里面的所有内容都是全局的。谢谢。 – 2013-03-24 21:08:18