【发布时间】: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