我无法让我的代码正常工作。我使用 XMLHttpRequest 加载和解析 JSON 文件,它工作正常,但是在我的 setup() 函数之后,我无法对我定义的任何变量(例如 spriteDictionary)调用任何其他函数 - 即使在各种设置函数中我可以读取这些变量,一切看起来都不错。
有什么想法吗?在下面的示例中,当我调用 console.log(parsedJSON); 它出现 undefined 这很奇怪,因为我可以在我的设置代码中读取它的内容。谢谢!
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body id="body">
</body>
<script type="application/x-javascript">
var parsedJSON;
var ctx;
var canvas;
var atlas;
var sprites = [];
var spriteDictionary = {};
var sprite = function(name, atl, x, y, w, h) {
this.name = name;
this.atlas = atl;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.cx = -w/2.0;
this.cy = -h/2.0;
}
function setup() {
var body = document.getElementById("body");
canvas = document.createElement("canvas");
canvas.width = 1200;
canvas.height =720;
body.appendChild(canvas);
var ctx = canvas.getContext('2d');
ctx.fillStyle="#000000";
ctx.fillRect(0,0,1200,720);
var xhr = new XMLHttpRequest();
xhr.open("GET","game_gfx.json",true);
xhr.onload = function (){
parsedJSON = JSON.parse(this.responseText);
load_assets(parsedJSON);
}
xhr.send();
ctx = canvas.getContext('2d');
}
function load_assets(pJSON) {
atlas = new Image();
atlas.onload = function() {
console.log("atlas loaded");
}
atlas.src= pJSON['meta']['image'];
var frame;
for (var i in pJSON['frames']){
frame = pJSON['frames'][i];
spriteDictionary[frame['filename']] = new sprite(frame['filename'],atlas,frame['frame']['x'],frame['frame']['y'],frame['frame']['w'],frame['frame']['h']);
i++;
}
}
setup();
console.log(parsedJSON);
</script>
</html>