我正在学习JavaScript和我的下一个项目我想用tileset游戏板和一些简单的机制来创建一个简单的RPG,虽然我可以让大多数后端函数工作正确我似乎无法让我的tileset正确呈现。
我目前只是试图降低逻辑,以便在tileset中的每个tile上呈现相同的图像,但是当我尝试渲染tileset时没有任何反应。检查控制台没有显示任何错误或问题,在搜索了几个教程后,我没有看到我的渲染会在哪里崩溃而不能工作,因为我只是尝试渲染1个单个40px x 40px灰色方块在每个瓷砖中。
这是指向我的相关代码要点的链接:https://gist.github.com/Randy-M/92c234a7a3cf8015bba6
以及它的原始粘贴:
//Creating the game tileset map
var c = document.getElementById('canvas');
var canvas = c.getContext('2d');
var tileImg = new Image();
tileImg.src = 'sampleTile.png';
var map = {
tiles: [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
],
tSize: 100,
rows: 5,
cols: 10,
getTile: function(row, col) {
return this.tiles[row][col];
}
};
//testGrid used to verify the map.getTile function successfully loops through all array values
var testGrid = function() {
for (r = 0; r < map.rows; r++) {
for (c = 0; c < map.cols; c++) {
var tile = map.getTile(r, c);
console.log(tile);
}
}
};
var renderMap = function() {
var x = map.cols * map.tSize;
var y = map.rows * map.tSize;
for (r = 0; r < map.rows; r++) {
for (c = 0; c < map.cols; c++) {
var tile = map.getTile(r, c);
if (tile != 0) {
canvas.drawImage(tileImg, x, y, map.tSize, map.tSize, c * map.tSize, r * map.tSize, map.tSize, map.tSize);
}
}
}
};
&#13;
HTML section is here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="mapContainer">
<canvas id="canvas" style="height: 720px; width: 1280px;"></canvas>
</div>
<button id="doStuff" onclick="renderMap()">draw canvas</button>
<script type="text/javascript" src="gameMap.js"></script>
</body>
</html>
&#13;
答案 0 :(得分:0)
var c = document.getElementById('canvas');
var canvas = c.getContext('2d');
var tileImg = new Image();
tileImg.src = 'http://vignette3.wikia.nocookie.net/gtawiki/images/b/b6/Flag_of_Japan_(bordered).png/revision/latest?cb=20100321220053';
var map = {
tiles: [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
],
rows: 5,
cols: 10,
getTile: function(row, col) {
return this.tiles[row[col]];
}
};
var renderMap = function() {
var size = 30;
var x = map.cols * size;
var y = map.rows * size;
for (r = 0; r < map.rows; r++) {
for (c = 0; c < map.cols; c++) {
var tile = map.getTile(r, c);
canvas.beginPath();
canvas.drawImage(tileImg, c * size, r * size, size, size);
canvas.stroke();
}
}
};
<button id="doStuff" onclick="renderMap()">draw canvas</button>
<div id="mapContainer">
<canvas id="canvas" style="height: 300px; width: 600px;"></canvas>
</div>
<script type="text/javascript" src="gameMap.js"></script>
我替换了日本国旗提供的图像,因为每个点现在代表一个成功放置的图块。