2016-12-03 99 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