2016-09-20 105 views
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; 
     } 
    } 
} 

回答

1

onload事件不會觸發,直到當前函數返回並且Javascript什麼都不做。 for循環使用變量i。當onload事件觸發時,我的值將是image.length,最後一個圖像的值爲1。

您需要使每個onload事件的變量對該調用唯一。你可以使用閉包來做到這一點。

如下

function drawMap(map, image, ctx, canvas, pos){ 

    function setOnLoad(i){ // this function creates closure over the variable i so 
          // that it is unique each time this function and the onload 
          // function runs. 
     var screenWidth = canvas.width; 
     var screenHeight = canvas.height; 
     var tileWidth = 0; 
     var tileHeight = 0; 
     var xPos = 0; 
     var yPos = 0; 
     // the following function closes over all the variables in this function 
     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; 
      } 
     } 
    } 
    for(var i = 0; i < image.length; i++){ 
     setOnLoad(i); 
    } 
} 

因此,你將有一個獨特的每一次的onload函數調用變量更改代碼。

相關問題