2017-04-13 63 views
-2

我的圖集不會顯示。這是什麼問題HTML5帆布,Tileset不會顯示

下面是一個代碼:

<!DOCTYPE html> 
<html> 

<head> 
    <style> 
    body { 
     margin: 0px; 
     padding: 0px; 
    } 

    #mapa { 
     border: solid 1px; 
    } 
    </style> 
</head> 

<body> <canvas id="mapa" height="500px" width="500px"></canvas> 
    <script> 
    var canvas = document.getElementById('mapa'); 
    var ctx = canvas.getContext('2d'); 
    var trawa = new Image(); 
    trawa.src = "trawa.png"; 
    var mapa = [ 
     [0, 0, 0, 0, 0, 1, 0, 0], 
     [0, 0, 0, 0, 0, 0, 0, 0] 
    ]; 
    var posX = 0; 
    var posY = 0; 
    for (var x = 0; x < mapa.length; x++) { 
     for (var y = 0; y < mapa[x].length; y++) { 
      if (mapa[x][y] == 0) { 
       ctx.drawImage(trawa, posX, posY, 32, 32); 
      } 
      posX += 50; 
     } 
     posX = 0; 
     posY += 50; 
    } 
    </script> 
</body> 

</html> 
+0

如果你有一個問題,你的代碼,包括** **它在的問題,並解釋它呢一個關於你遇到的問題的上下文 –

+0

請不要通過pastebin鏈接添加代碼,該鏈接可能會在以後的任何日期無效,在stackoverflow問題編輯器窗口中有設置將HTML/Javascript嵌入到您的問題中,觀衆甚至可以運行你的代碼而不必離開這個ta灣 –

回答

0

這裏的問題是,圖像尚未加載,當您嘗試畫它,你需要做的是等待,直到它被加載。

對於您可以使用trawa.onload如下:

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <style> 
 
    body { 
 
    margin: 0px; 
 
    padding: 0px; 
 
    } 
 
#mapa 
 
{ 
 
    border: solid 1px; 
 
} 
 
    </style> 
 
</head> 
 
<body> 
 

 
<canvas id = "mapa" height = "500px" width= "500px"></canvas> 
 

 
<script> 
 

 
var canvas = document.getElementById('mapa'); 
 
var ctx = canvas.getContext('2d'); 
 

 
var trawa = new Image(); 
 
trawa.src = "trawa.png"; 
 

 

 
var mapa = [ 
 
[0,0,0,0,0,1,0,0], 
 
[0,0,0,0,0,0,0,0] 
 
]; 
 
var posX = 0; 
 
var posY = 0; 
 

 
trawa.onload = function(){ 
 
    for (var x = 0; x < mapa.length; x++){ 
 

 
    for (var y = 0; y < mapa[x].length; y++) 
 
    { 
 

 
     if (mapa[x][y] == 0) 
 
     { 
 
     ctx.drawImage(trawa, posX, posY, 32,32); 
 
     } 
 

 
    posX+=50; 
 

 
    } 
 
    posX = 0; 
 
    posY+=50; 
 
    } 
 

 
} 
 

 
</script> 
 

 
</body> 
 
</html>