I am currently following a tutorial on how to load JSON map files created by the Tiled Map Editor in my JavaScript/Canvas game. So far, I have implemented my own version without any errors showing up in Firebug or the console.
Upon closer inspection with console.logs and alerts, it seems that the script is running perfectly fine. However, the canvas remains blank when it should display a tilemap.
Below is my implementation of the tutorial in my game:
function Level() {
var c;
var data;
var layers = [];
this.get_map = function(name, ctx) {
c = ctx;
$.getJSON('maps/' + name + '.json', function(json) {
get_tileset(json);
});
};
function get_tileset(json) {
data = json;
this.tileset = $("<img />", { src: json.tilesets[0].image })[0];
this.tileset.onload = renderLayers(this);
}
function renderLayers(layers) {
layers = $.isArray(layers) ? layers : data.layers;
layers.forEach(renderLayer);
}
function renderLayer(layer) {
if (layer.type !== "tilelayer" || !layer.opacity) {
alert("Not a tileLayer");
}
var s = c.canvas.cloneNode(),
size = data.tileWidth;
s = s.getContext("2d");
if (layers.length < data.layers.length) {
layer.data.forEach(function(tile_idx, i) {
if (!tile_idx) { return; }
var img_x, img_y, s_x, s_y,
tile = data.tilesets[0];
tile_idx--;
img_x = (tile_idx % (tile.imagewidth / size)) * size;
img_y = ~~(tile_idx / (tile.imagewidth / size)) * size;
s_x = (i % layer.width) * size;
s_y = ~~(i / layer.width) * size;
s.drawImage(this.tileset, img_x, img_y, size, size,
s_x, s_y, size, size);
});
layers.push(s.canvas.toDataURL());
c.drawImage(s.canvas, 0, 0);
} else {
layers.forEach(function(src) {
var i = $("<img />", { src: src })[0];
c.drawImage(i, 0, 0);
});
}
}
}
The above code is called from my main JavaScript file as shown below:
$(document).ready(function() {
var canvas = document.getElementById("TBG");
var ctx = canvas.getContext("2d");
var ui = new Gui();
var level = new Level();
// ... (Additional JavaScript code)
});
Despite everything seeming correct in the code, the tile-map still fails to show up on my canvas. Any suggestions or assistance would be greatly appreciated. Thank you for your help!
Sincerely, Tom