gpt4 book ai didi

javascript - 在 Javascript 中显示 tilemap

转载 作者:行者123 更新时间:2023-11-30 19:39:19 27 4
gpt4 key购买 nike

这是我现在用来尝试生成 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
);
}
}
}
}
}

这里是 spritesheet

它应该显示一个 8x8 的“草地”网格,但它是空白的,但控制台是清晰的

最佳答案

您拼错了 tsize(相对于 tSize)。此外,第二个参数的表达式似乎不是您想要的。你可以只传递一个 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 = '/image/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>

关于javascript - 在 Javascript 中显示 tilemap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com