简体   繁体   English

HTML5画布绘制图块

[英]HTML5 Canvas draw tileset

Something like I'm have tileset: 就像我有tileet一样:

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: 我的tileet绘制代码:

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? 这段代码绘制了“ 5”图块,但是类似如何绘制10图块? or 15 tile without adding tileX, tileY. 或15个图块,但不添加tileX,tileY。 I'm need something like if tile equal to 15 - draw 15 tile. 我需要类似15的瓷砖-绘制15瓷砖。

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. 将这些tilset坐标放置在(多维)数组中,这样您就可以遍历数据并显示结果。 It means that if there are 10 items your code will loop through all ten. 这意味着如果有10个项目,您的代码将遍历所有十个项目。 If there are 15, then fine, it'll loop through all 15. 如果有15个,那么很好,它将遍历所有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). 当然,如果使用for循环并将结束条件指定为“ i <tile”(假设您的计数从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. '1,7'=一张,在我的Sprite表上向下7。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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