2016-12-03 100 views
0

我有一個html畫布,它顯示在輸入中選擇圖像時預覽圖像。這適用於Chrome,但我似乎無法讓它在Safari中運行。特別是 - 在Safari中,onchange="previewFile()"似乎沒有調用previewFile函數。輸入onchange JavaScript函數調用不工作在Safari中

<canvas id="canvas" width="0" height="0"></canvas> 
 

 
<h2>Upload a photo </h2> 
 
<input type="file" onchange="previewFile()"><br> 
 

 
<script type="text/javascript"> 
 

 
    // setup the canvas 
 
    var canvas = document.getElementById('canvas'); 
 
    var ctx = canvas.getContext('2d'); 
 

 
    // grab the photo and display in canvas 
 
    var photo = new Image(); 
 
    function previewFile() { 
 
     var file    = document.querySelector('input[type=file]').files[0]; 
 
     var reader  = new FileReader();  
 

 
     reader.addEventListener("load", function() { 
 
      photo.src = reader.result; 
 
      canvas.height = photo.height; 
 
      canvas.width = photo.width; 
 
      ctx.drawImage(photo,0,0); 
 
     }, false); 
 

 
     if (file) { 
 
    reader.readAsDataURL(file); 
 
     }  
 
    } 
 

 
</script>

回答

1

你的問題肯定是由於這樣的事實,你是不是等待圖像加載你試圖畫在畫布上之前。

即使源是dataURI,圖像的加載也是異步的,因此您需要將圖形操作包裝在圖像的onload事件中。

var photo = new Image(); 
photo.onload = function(){ 
    canvas.height = photo.height; 
    ... 
    } 
... 
reader.onload = function(){ 
    // this will eventually trigger the image's onload event 
    photo.src = this.result; 
    } 

但是,如果你需要的是吸引你的形象在畫布上,甚至不使用的FileReader,實際上,readAsDataURL()方法將引發你的大腦I'm doing something wrong錯誤。幾乎所有你可以用一個Blob的dataURI版本來做,你也可以用Blob自己做,而不用計算它,也不會污染瀏覽器的內存。

例如,要顯示用於用戶輸入的圖像,可以使用URL.createObjectURL(blob)方法。

// setup the canvas 
 
var canvas = document.getElementById('canvas'); 
 
var ctx = canvas.getContext('2d'); 
 

 
// grab the photo and display in canvas 
 
var photo = new Image(); 
 
// drawing operations should be in the mage's load event 
 
photo.onload = function() { 
 
    // if you don't need to display this image elsewhere 
 
    URL.revokeObjectURL(this.src); 
 

 
    canvas.height = this.height; 
 
    canvas.width = this.width; 
 
    ctx.drawImage(this, 0, 0); 
 
} 
 
photo.onerror = function(e) { 
 
    console.warn('file format not recognised as a supported image'); 
 
} 
 
file_input.onchange = function() { 
 
    // prefer 'this' over DOM selection 
 
    var file = this.files[0]; 
 
    var url = URL.createObjectURL(file); 
 
    photo.src = url; 
 
};
<canvas id="canvas" width="0" height="0"></canvas> 
 

 
<h2>Upload a photo </h2> 
 
<input type="file" id="file_input"> 
 
<br>

而對於那些誰需要這個文件發送到他們的服務器,使用FormData直接發送斑點。如果你確實需要一個dataURI版本,那麼將其轉換爲服務器端。

+0

非常感謝!這解決了問題,你教了我一兩件事! – rcrusoe