【问题标题】:Wait for img.onload inside a synchronious function在同步函数中等待 img.onload
【发布时间】:2021-10-16 14:12:45
【问题描述】:

我有一种情况,我需要等待 img.onload 函数来调整图片大小。 img.onload 函数位于同步函数中,不能异步。 我需要等待 img.onload 才能继续同步函数。

有人知道如何实现它吗?

例子:

  function test(img) {
    const img =  new Image();

    img.onload = function () {
       //Here needs something to happen, set a variable
       x = value;
    };

    //After the img.onload I need to access this here
    console.log(x);
  }

这是我目前所拥有的。 我知道 img.onload 将在稍后执行,并且在此之前触发 console.log(x),但它需要在之后执行。遗憾的是,我不能只将其移至 img.onload 中,因为此功能测试用于上传,否则将无法正常工作。

感谢任何提示。

编辑:

上传前我用来调整图片大小的实际代码。 上传发生在测试函数中,在这段代码之后:

img.onload = function () {
    URL.revokeObjectURL(this.src);
    const [newWidth, newHeight] = calculateSize(img, MAX_WIDTH, MAX_HEIGHT);
    const canvas = document.createElement("canvas");
    canvas.width = newWidth;
    canvas.height = newHeight;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, newWidth, newHeight);
    canvas.style = "display: none";
    canvas.toBlob(
        (blob) => {
            // Handle the compressed image. es. upload or save in local state
            let file_small = new File([blob], name,{type:"image/jpeg", lastModified:new Date().getTime()});
            let container = new DataTransfer();
            container.items.add(file_small);
            ajaxData.set('upload', container.files[0]);
            console.log("END of the onload");
                },
            MIME_TYPE,
            QUALITY
        );
};

【问题讨论】:

  • 可以在 Image 函数中使用 Promises 吗?
  • 我想是的,但你会怎么做呢?
  • 能否提供Image功能代码?所以我可以给你一个解决方案
  • 我编辑了 onload 中的代码!

标签: javascript html image upload


【解决方案1】:

以下是示例,但您可以根据需要进行更新。

async function test() {
  const myImage = new Image(100, 200);
  myImage.src = 'https://images.kiwi.com/airlines/128x128/0B.png';
  document.body.appendChild(myImage);
  await callFunction(myImage);
  console.log('called second');
}

function callFunction(img) {
  return new Promise((resolve, reject) => {
    img.onload = () => {
        //here you all code goes
        console.log('called first');
        resolve(true)
    }
  })
}

test()

如果这是一个解决方案,请投票给一个有用的答案,提前谢谢你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 2020-12-31
    • 2021-10-16
    • 2022-07-06
    • 2018-01-15
    • 1970-01-01
    • 2023-03-13
    • 2019-04-06
    相关资源
    最近更新 更多