2012-02-13 91 views
1

我正在學習HTML5和Javascript,我試圖在畫布上繪製圖像。如果我在打破下面標記的行之後遍歷代碼,我有以下代碼可以繪製圖像。如果我不調試,那麼圖像根本就沒有繪製。我究竟做錯了什麼?火狐10與FireBug 1.9。爲什麼在調試時在畫布上繪製圖像,但在運行時不能繪製圖像?

請注意,雖然有一個循環來處理多個圖像,但我只選擇了一個。我認爲如果一個人不工作,一個人也不會工作。 ;-)

<!DOCTYPE html> 
<html> 
<body> 
    <input type="file" id="files" name="files[]" multiple /> 
    <canvas id="picCanvas" /> 
    <script> 
     function handleFileSelect(evt) { 
      var files = evt.target.files; 

      // Loop through the FileList and render images 
      for (var i = 0, f; f = files[i]; i++) { 

       // Only process image files. 
       if (!f.type.match('image.*')) { 
        continue; 
       } 

       var reader = new FileReader(); 

       // Closure to capture the file information. 
       reader.onload = (function (theFile) { 
        return function (e) { 
         var img = document.createElement('img'); // <-- BREAK HERE! 
         img.src = e.target.result; 

         var canvas = document.getElementById('picCanvas'); 
         canvas.width = img.width; 
         canvas.height = img.height; 
         var ctx = canvas.getContext('2d'); 
         ctx.drawImage(img, 0, 0); 
        }; 
       })(f); 

       // Read in the image file as a data URL. 
       reader.readAsDataURL(f); 
      } 
     } 

     document.getElementById('files').addEventListener('change', handleFileSelect, false); 
    </script> 
</body> 
</html> 

回答

6

你必須等待,直到圖像元素是由瀏覽器調用drawImage方法完全加載之後,即使從一個base64字符串創建你的圖像元素,而不是從外部文件。所以只需使用圖像對象的onload事件即可。快速解決將是這樣的:

var img = document.createElement('img'); 

img.onload = function() 
{ 
    var canvas = document.getElementById('picCanvas'); 
    canvas.width = this.width; 
    canvas.height = this.height; 
    var ctx = canvas.getContext('2d'); 
    ctx.drawImage(this, 0, 0); 
} 

img.src = e.target.result; 
+0

非常感謝三角洲!有趣的是,答案現在如此明顯。 :-) – KatoMan 2012-02-13 12:31:58