gpt4 book ai didi

javascript - 输入 onchange javascript 函数调用在 Safari 中不起作用

转载 作者:行者123 更新时间:2023-12-03 05:30:55 24 4
gpt4 key购买 nike

我有一个 html Canvas ,当在输入中选择图像时,它会显示图像的预览。这在 Chrome 中有效,但我似乎无法让它在 Safari 中工作。具体来说 - 在 Safari 中 - onchange="previewFile()" 似乎没有调用 PreviewFile 函数。

<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>

最佳答案

您的问题肯定是由于您在尝试在 Canvas 上绘制图像之前没有等待图像加载。

即使源是 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;
}

但是,如果您需要的只是在 Canvas 上绘制图像,甚至不要使用 FileReader,实际上,readAsDataURL() 方法应该触发 我正在做某事你的大脑出现了错误错误。几乎您可以使用 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 直接发送 Blob。如果您确实需要 dataURI 版本,请在服务器端将其转换。

关于javascript - 输入 onchange javascript 函数调用在 Safari 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40950894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com