JavaScript图像压缩递归



我有以下功能,用户可以上传图像,然后压缩它们。这里的问题是,当我在image.onload函数中console.log(e.target)时,它会在控制台中连续显示它,这意味着它是递归的,它冻结了我的应用程序,不能做任何其他事情。

这种压缩方法我从下面的YouTube视频中获得,并试图采用我所拥有的。https://www.youtube.com/watch?v=bXf_UdyDzSA&ab_channel=代码%C3%BACommunity

function addImageToForm(e) {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
let files = e.target.files;
if (numberOfImages + files.length > 4) {
alert("You can only upload at most 4 files!");
return;
}
numberOfImages += files.length;
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.addEventListener("load", function (e) {  
console.log(this);
let imageFile = e.target;
let divDocument = document.createElement("div");
let image = document.createElement("img");
divDocument.setAttribute("class", "id-document");
image.setAttribute("class", "image-preview");
image.setAttribute(
"style",
"width: inherit; height: inherit; border-radius: 20px;"
);
image.setAttribute("src", imageFile.result);
image.onload = function (e) {
let canvas = document.createElement("canvas");
let MAX_WIDTH = 200;
let scaleSize = MAX_WIDTH / e.target.width;
canvas.width = MAX_WIDTH;
canvas.height = e.target.height * scaleSize;
let ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);
console.log(e.target);
let srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
image.setAttribute("src", srcEncoded);
}
divDocument.appendChild(image);
rowOfPhotos.appendChild(divDocument);
});
const reference = firebase
.storage()
.ref(`${user.displayName}/game_images/` + file.name);
reference
.put(file)
.then((snapshot) => snapshot.ref.getDownloadURL())
.then((url) => {
imagesArray.push(url);
});
} else {
image.style.display = null;
}
}
} else {
console.log("Not logged in");
}
});
}

有人看到问题出在哪里了吗?

这是因为,您在onload函数中更改了图像src

image.setAttribute("src", srcEncoded);

每次更改图像src时,都会调用onload函数。

相关内容

  • 没有找到相关文章

最新更新