2013-02-14 143 views
2

我正在開發一個web開發實驗室,但我的圖像沒有顯示出來。有沒有什麼我在做錯了參考圖像?這裏是一個鏈接到圖像本身:http://tuftsdev.github.com/WebProgramming/assignments/pacman10-hp-sprite.pngHTML5/JS在Canvas中不呈現圖像。

注:我將圖像複製到我的本地目錄,所以我知道引用是正確的。

<!DOCTYPE html> 
<html> 
<head> 
    <title>Ms. Pacman</title> 
    <script> 
     function draw() { 
      canvas = document.getElementById('simple'); 

      // Check if canvas is supported on browser 
      if (canvas.getContext) { 
       ctx = canvas.getContext('2d'); 
       var img = new Image(); 
       img.src = '"pacman10-hp-sprite.png'; 
       ctx.drawImage(img, 10, 10); 
      } 
      else { 
       alert('Sorry, canvas is not supported on your browser!'); 
      } 
     } 
    </script> 
    </head> 

<body onload="draw();"> 
    <canvas id="simple" width="800" height="800"></canvas> 
</body> 
</html> 

回答

2

你需要建立一個回調和圖像繪製在畫布上的圖像一旦實際加載:

function draw() { 
    canvas = document.getElementById('simple'); 

    // Check if canvas is supported on browser 
    if (canvas.getContext) { 
     ctx = canvas.getContext('2d'); 
     var img = new Image(); 

     // If you don't set this callback before you assign 
     // the img.src, the call ctx.drawImage will have 
     // a null img element. That's why it was failing before 
     img.onload = function(){ 
      ctx.drawImage(this, 10, 10); 
     }; 

     img.src = "pacman10-hp-sprite.png"; 
    } else { 
     alert('Sorry, canvas is not supported on your browser!'); 
    } 
}