如何等到 image.src 在 image.onload 事件函数中设置?

在我的新 image() 对象的浏览器 javascript 中,对于 onload 事件,我首先在用户选择图像文件后设置 image.src ;然后读取图像对象的大小。


但似乎读取发生在正确设置 src 之前。我碰巧找到了两次调用该函数的修复方法。但是这个解决方案似乎是一个非常糟糕的主意。


请让我知道如何以标准方式修复它。我的环境接受打字稿。


var imgLoaded=false;

 var file = document.getElementById("fileInput").files[0];

      for(let i=0;i<2;i++){    

          call2(file);

         }

      


   function call2(file) {

      var reader = new FileReader();

      reader.readAsDataURL(file);


      reader.onload = function () {

          if(!imgLoaded){ 

              imgLoaded=true;   img.src=(reader.result).toString();}

         else{

        console.log(img.width);

      }}


眼眸繁星
浏览 148回答 3
3回答

慕后森

在一种方式中,您可以替换&nbsp;file = document.getElementById("fileInput").files[0];为file = event.target.files[0]&nbsp;并在 call2 中使用它,您还应该将事件传递给 call2例如:在 html 中:&nbsp;<input type="file" onchange="call2(event)" />,然后在 js 中function call2(e){let file = e.target.files[0] ... }

阿波罗的战车

await (img.src= await (reader.result).toString())也可以。无需调用控制台。

慕码人2483693

我自己至少找到了一个更好的解决方案。虽然我不知道这是否是一个标准。&nbsp;var file = document.getElementById("fileInput").files[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; call2(file);&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function call2(file) {&nbsp; &nbsp; &nbsp; var reader = new FileReader();&nbsp; &nbsp; &nbsp; reader.readAsDataURL(file);&nbsp; &nbsp; &nbsp; reader.onload =async function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;img.src= await (reader.result).toString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(await img.width);&nbsp; &nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript