0
我想使用畫布繪製平鋪地圖。有三種類型的圖塊需要繪製到畫布上,所以不是每次爲每個圖像調用三次函數,而是將一組圖像作爲參數傳遞,循環遍歷數組,並將畫布告訴給繪製每個圖像。但是,當我這樣做時,我得到一個空白的畫布,沒有返回錯誤消息。當我不傳入一個數組,而是爲每個圖像手動進行函數調用時,圖像將被繪製到畫布上。任何人都可以向我解釋我做錯了什麼?爲什麼圖像數組不能在HTML5畫布中繪製?
window.onload = function(){
var basemap = document.getElementById("basemap");
var basemapCtx = basemap.getContext("2d");
initMap(Map.map, basemapCtx, basemap);
}
function initMap(map, ctx, canvas){
var deepWater = new Image();
var shallowWater = new Image();
var coastalWater = new Image();
deepWater.src = "deepWater.png";
shallowWater.src = "shallowWater.jpg";
coastalWater.src = "coastalWater.jpg";
//Does not draw the images
drawMap(map, [deepWater, shallowWater, coastalWater], ctx, canvas, [-2, -1, 0]);
//Does draw the images
//drawMap(map, deepWater, ctx, canvas, -2);
//drawMap(map, shallowWater, ctx, canvas, -1);
//drawMap(map, coastalWater, ctx, canvas, 0);
}
function drawMap(map, image, ctx, canvas, pos){
var screenWidth = canvas.width;
var screenHeight = canvas.height;
var tileWidth = 0;
var tileHeight = 0;
var xPos = 0;
var yPos = 0;
for(var i = 0; i < image.length; i++){
image[i].onload = function(){
for(var rows = 0; rows < map.length; rows++){
tileHeight = (screenHeight/map.length);
for(var cols = 0; cols < map[rows].length; cols++){
tileWidth = (screenWidth/map[rows].length);
if(map[rows][cols] == pos[i]){
ctx.drawImage(image[i], xPos, yPos, tileWidth, tileHeight);
}
xPos += tileWidth;
}
xPos = 0;
yPos += tileHeight;
}
yPos = 0;
tileWidth = 0;
tileHeight = 0;
}
}
}