<canvas id="canvas" width="640" height="480"></canvas>
我在 HTML5 Canvas ( )中有一个示例。这是 JavaScript 代码(JSFiddle 链接):
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var table = new Image();
table.src = 'http://s1.postimage.org/188qzfays/table.png';
var image1 = new Image();
var image2 = new Image();
image1.src = 'http://s4.postimage.org/1fxt9xtyc/floor_standard.png';
image2.src = 'http://s2.postimage.org/1a4erdun8/floor_standard2.png';
var objImage = new Image();
objImage.src = 'http://s4.postimage.org/1fxzw37xg/tree.png';
var tileArray = [image1, image2];
var objArray = [objImage];
var tileW = 16;
var tileH = 16;
var map = [
[1, 0, 0, 0, 0],
[0, 1, 1, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 1, 0]
];
var objMap = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
for(var i = 0; i < map.length; i++) {
for(var j = 0; j < map[i].length; j++) {
var drawTile = map[i][j];
var objTile = objMap[i][j];
var xpos = (i-j) * tileH + 100;
var ypos = (i+j) * tileH / 2 + 100;
context.drawImage(tileArray[drawTile], xpos, ypos);
if(objMap) {
context.drawImage(objArray[objTile], xpos, ypos - 32);
}
}
}
这个例子可以渲染等距平铺和等距物体,但我只能在一个平铺上绘制物体(例如,我不能在 4 个平铺上绘制物体)。如何在多个图块中绘制等距对象?类似这个对象的东西(在我的代码中,它存储在一个名为 table 的变量中):