Reputation: 13
Here is the code I'm using right now to try to generate a tilemap:
// --- Javascript ---
window.onload = function (){
var can = document.getElementById("canvas");
var ctx = can.getContext('2d');
var map = {
cols: 8, //# of cols
rows: 8, // # of rows
tSize: 32, // tile size (32px x 32px)
tiles: [
[1, 1, 1, 1 ,1 ,1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1]
], // map
};
var tileAtlas = new Image();
tileAtlas.src = 'Tiles.png';
tileAtlas.onload = function () {
for (var c = 0; c < map.cols; c++) {
for (var r = 0; r < map.rows; r++) {
if (map.tiles[c][r] !== 0) { // 0 is an empty tile
ctx.drawImage(
tileAtlas, // image
map.tiles[c][r] * 32, // cut start x
0, // cut start y
map.tsize, // size of tiles for cut size x
map.tsize, // size of tiles for cut size y
c * map.tsize, // place tiles on canvas x
r * map.tsize, // place tiles on canvas y
map.tsize, // place height
map.tsize // place width
);
}
}
}
}
}
here is the spritesheet
It was supposed to show an 8x8 grid of "grass" but it was blank yet the console was clear
Upvotes: 1
Views: 613
Reputation: 351218
You misspelled tsize
(versus tSize
). Also, the expression for the second argument seems not what you want. You can just pass a 0:
ctx.drawImage(
tileAtlas, // image
0,
0,
map.tSize, // size of tiles for cut size x
map.tSize, // size of tiles for cut size y
c * map.tSize, // place tiles on canvas x
r * map.tSize, // place tiles on canvas y
map.tSize, // place height
map.tSize // place width
);
var can = document.getElementById("canvas");
var ctx = can.getContext('2d');
var map = {
cols: 8, //# of cols
rows: 8, // # of rows
tSize: 32, // tile size (32px x 32px)
tiles: [
[1, 1, 1, 1 ,1 ,1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1]
], // map
};
var tileAtlas = new Image();
tileAtlas.src = 'https://i.sstatic.net/2JX3d.png';
tileAtlas.onload = function () {
for (var c = 0; c < map.cols; c++) {
for (var r = 0; r < map.rows; r++) {
ctx.drawImage(
tileAtlas, // image
0,
0,
map.tSize, // size of tiles for cut size x
map.tSize, // size of tiles for cut size y
c * map.tSize, // place tiles on canvas x
r * map.tSize, // place tiles on canvas y
map.tSize, // place height
map.tSize // place width
);
}
}
}
<canvas id="canvas" width="256px" height="256px"></canvas>
Upvotes: 1