Recently I made the switch from Map Tiler to Tiled for my map creation. With Map Tiler, I got multiple arrays (one for each level of the X axis), but with Tiled, I'm dealing with one long array.
Initially, when working with Map Tiler, I would do:
for (var y = 0; y <= 15; y++) {
for (var x = 0; x <= 0; x++) {
// draw map board[0][13] for example
// then tileX *32 and tileY *32 being the spritesheet being cut
context.drawImage(imageObj, tileX * 32, tileY * 32, 32, 32, x*32, y*32, 32, 32)
}
}
Now, however, I am facing difficulties in drawing a simple map using the single long array format.
The tileset I'm working with can be viewed here: https://i.sstatic.net/OkU1c.png, and this is what it looks like: https://i.sstatic.net/drh5Z.png
The main question at hand is, how can you extract the current 15x10 required arrays from that larger 400-element array so they can be displayed on the canvas?
// Canvas viewport size is 15 tiles wide, 10 tiles tall
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d')
var imageObj = new Image()
imageObj.src = 'https://i.sstatic.net/OkU1c.png'
var client = {
'vWidth': 15,
'vHeight': 10,
'imageWidth': 159,
'imageHeight': 32
}
var tilesX = client.ImageWidth / 32
var tilesY = client.ImageHeight / 32
// Extracting the correct 15x10 canvas from a single 400-element array
// Desired map view should resemble this: https://i.sstatic.net/drh5Z.png
imageObj.onload = function () {
context.drawImage(imageObj, 0, 0)
var getTile = 0
for (var y = 0; y <= client.vHeight; y++) {
for (var x = 0; x <= client.vWidth; x++) {
// Need to find a way during each loop through the canvas (of the size 15x10) to locate the right tile from the larger array
// starting from 0,0... after every 15 loops [client.vWidth] (for painting the map), within the BOARD...
// skip 20 array elements before continuing from where you left off earlier
// Find the correct tile
var tile = (board()[getTile])
// Positioning on canvas
var theX = x * 32
var theY = y * 32
var tileY = Math.floor(tile / tilesX)
var tileX = Math.floor(tile % tilesX)
console.log('Tile: ' + tile + ', TileY: ' + tileY + ', TileX: ' + tileX)
context.drawImage(imageObj, tileX * 32, tileY * 32, 32, 32, theX, theY, 32, 32)
getTile++
}
}
}
function board() {
return [*(Large 400 element array)*]
}
//console.log(board);
#canvas {
background: grey;
}
<canvas id="canvas" height="352" width="512"></canvas>
Take a look at this reference image which demonstrates the desired output from the lengthy board()
array:
https://i.sstatic.net/8Z0nF.jpg
You can see what I have accomplished so far here: https://jsfiddle.net/3fx58ock/