我正在drawImage
尝试绘制瓷砖和玩家。它可以工作,但是它首先绘制玩家然后绘制瓷砖。这应该是相反的,因为现在我看不到我的播放器。
我怎么知道我的球员被抽中了?因为如果我取出绘制瓷砖的东西(if (loadedImagesCount==NUM_OF_TILES) draw();
),那么我可以看到我的玩家。此外,总是会弹出提示玩家已被绘制的消息。
帮助?
这是我的代码:
// HTML5 JS Tile Example
var canvas, context, board, imageObj, tiles;
var currentMap = 1;
var upMap = 0;
var rightMap = 0;
var leftMap = 0;
var downMap = 3;
var NUM_OF_TILES = 16; // starting from ZERO
var spawnX = 9; // spawn on X position
var spawnY = 7; // spawn on Y position
var playerImg = new Image();
var currX = 9; // current X position
var currY = 7; // current Y position
// Set return 2D array of map
function loadMap(map) {
if (map == 1) {
return [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 13, 1, 13, 1, 13, 1, 13, 13, 13, 13, 13, 1, 13, 13, 1], [1, 13, 13, 13, 1, 13, 1, 13, 1, 13, 13, 13, 1, 13, 13, 1], [1, 13, 13, 13, 13, 13, 1, 13, 1, 13, 1, 13, 1, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 1, 13, 1, 13, 13, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1, 13, 13, 13, 13, 1], [1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 13, 1, 1, 1, 1, 1, 1]
];
}
}
var drawPlayer = function() {
realSpawnX = spawnX * 32;
realSpawnY = spawnY * 32;
playerImg.src = "me.gif";
context.drawImage(playerImg, realSpawnX, realSpawnY, 32, 32);
console.log("Player drawn at (" + spawnX + "," + spawnY + ") Real spawn: X: " + realSpawnX + " Y: " + realSpawnY);
}
window.onload = function () {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
imageObj = new Image();
tiles = [];
board = loadMap(1);
canvas.width = 512;
canvas.height = 352;
// Draw the player .,.. now
drawPlayer();
var draw = function() {
var theX;
var theY;
// 3. DRAW MAP BY ROWS AND COLS
for (x = 0; x <= 10; x++) {
for (y = 0; y <= 15; y++) {
theX = x * 32;
theY = y * 32;
context.drawImage(tiles[board[x][y]], theY, theX, 32, 32);
}
}
}
var loadedImagesCount = 0;
// 2. SET UP THE MAP TILES
for (x = 0; x <= NUM_OF_TILES; x++) {
var imageObj = new Image(); // new instance for each image
imageObj.src = "line_tile/t" + x + ".png";
imageObj.onload = function() {
loadedImagesCount++;
if (loadedImagesCount==NUM_OF_TILES) draw();
};
tiles.push(imageObj);
}
};