简体   繁体   中英

HTML5 Canvas draw tileset

Something like I'm have tileset:

0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16,
17, 18, 19, 20

My tileset draw code:

var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
context.drawImage(image, Math.floor(tile * tileSize), 0, tileSize, tileSize, x, y, tileSize, tileSize);

And this code draw '5' tile, but something like how to draw 10 tile? or 15 tile without adding tileX, tileY. I'm need something like if tile equal to 15 - draw 15 tile.

Sorry for my poor english language.

Thanks!

Put those tilset co-ordinates in a (multi dimensional) array, that way you can loop through the data and display the results. It means that if there are 10 items your code will loop through all ten. If there are 15, then fine, it'll loop through all 15.

Of course you can limit how many tiles if you loop through by using a for loop and specifying the end condition as "i < tile" (assuming your count starts at 0).

Let me know if I haven't quite understood you. Below is an example of a function I created for a project of mine to draw tiles. It might give you some clues to what you're trying to do.

function renderMap(ctx, mapObj)
{
var rgt = mapObj.data();        

for (matrixY in rgt) {
    for (matrixX in rgt[matrixY]) {

        var matrixArray = rgt[matrixY][matrixX].split(',');

        var x = matrixArray[0];
        var y = matrixArray[1];

        var sx = (x-1) * mapObj.tileWidth();
        var sy = (y-1) * mapObj.tileHeight();

        var dx = (matrixX) * mapObj.tileWidth();
        var dy = (matrixY) * mapObj.tileHeight();

        ctx.drawImage(mapObj.mapTilesImg(), sx, sy, mapObj.tileWidth(), mapObj.tileHeight(), dx, dy, mapObj.tileWidth(), mapObj.tileHeight());
    }
}
}

And the data used (part of a track object):

    rgt: [  ['1,7', '1,7', '1,7', '1,7', '1,7', '1,7', '1,7', '1,7'],
            ['1,2', '2,1', '4,4', '2,1', '2,4', '2,1', '2,1', '2,2'],   
            ['3,4', '4,5', '1,7', '1,7', '4,13', '1,7', '1,7', '1,4'],
            ['4,3', '1,7', '3,7', '1,7', '1,7', '1,2', '2,1', '2,6'],
            ['1,1', '1,15', '1,7', '1,7', '2,7', '1,4', '1,7', '1,7'],
            ['1,6', '2,1', '2,1', '2,4', '4,1', '2,6', '1,7', '1,7']
        ]

I've used co-ordinates. eg. '1,7' = one across, 7 down on my sprite sheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM