【发布时间】:2015-11-08 22:45:22
【问题描述】:
所以我最近将我的地图从 Map Tiler(或其他)切换到 Tiled。原始地图平铺器为我提供了多个数组(对于 X 轴的每个级别),而 Tiled 以一个长数组返回地图。
所以我会这样做,
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)
}
}
现在我很难使用长数组绘制简单的地图。
我的图块集:http://i.imgur.com/WTd6quW.png,它会是什么样子:http://i.imgur.com/IiiGEBN.png
问题是,您将如何尝试从 400 个元素的数组中获取当前所需的 15x10 数组,同时尝试在画布上绘制它?
// Viewport of canvas is 15 tiles wide, 10 tiles tall
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d')
var imageObj = new Image()
imageObj.src = 'http://i.imgur.com/WTd6quW.png'
var client = {
'vWidth': 15,
'vHeight': 10,
'imageWidth': 159,
'imageHeight': 32
}
var tilesX = client.ImageWidth / 32
var tilesY = client.ImageHeight / 32
// Get the correct 15x10 canvas from a single 400-element array
// Map should look like this: http://i.imgur.com/IiiGEBN.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++) {
// Somehow as you go thru the canvas on every x,y of (15x10)...
// there has to be a way to getting the correct tile of the map
// starting from 0,0... so once every 15 loops [client.vWidth] (for painting of map), on the BOARD...
// skip 20 array elements and THEN start painting from where you last left off
// Get the correct tile
var tile = (board()[getTile])
// For 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 [2, 2, 2, 2, 2, 2, 2, 2, 2, 2,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5, 5, 5, 5, 5, 5, 5, 5, 2, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
}
//console.log(board);
#canvas {
background: grey;
}
<canvas id="canvas" height="352" width="512"></canvas>
此参考图片会有所帮助。这就是我试图从那个长 board() 数组中完成的任务。
【问题讨论】:
-
所以您只是想获得正确的图块索引?喜欢
y * client.vWidth + x? -
如果你的地图是 15x10,为什么你的数组有 400 个元素而不是 150 个?
-
@rrowland 因为视口是 15x10,地图是 20x20。
标签: javascript arrays canvas