コードを動作させるのに問題があります。正常に動作する XMLHttpRequest を使用して JSON ファイルを読み込んで解析しますが、setup() 関数の後、spriteDictionary など、定義した変数に対して他の関数を呼び出すことはできません。これらの変数を読み取ることができ、すべて問題ないように見えます。
何かご意見は?以下のサンプルでは、console.log(parsedJSON); を呼び出します。セットアップコードでその内容を読み取ることができるので、これは奇妙です。ありがとう!
<!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>