我希望上传到我的网站上的图片必须是纵向或正方形的,而且我不想裁剪图片。上传的图片必须默认为纵向或正方形,我已经搜索了许多网站和方法,但没有一个方法能够实现。
现在我正在尝试这种方法,但它也不起作用,因为它是异步运行的。
如果在给定的代码中提供横向图像,则它会运行,这是不应该发生的,因为hasError
必须为true,但实际上不是,因为if条件在上面的代码完成之前就运行了。那我该怎么办呢?
let hasError = false;
image = event.target.files[0];
if (image) {
var img = new Image();
img.src = window.URL.createObjectURL(image);
img.onload = function () {
height = img.naturalHeight;
width = img.naturalWidth;
console.log(hasError); // prints false
if (height < width) {
hasError = true; // prints true
console.log(hasError);
}
window.URL.revokeObjectURL(img.src);
}
console.log(hasError); //prints flase
}
if(!hasError){
....
}
img.onload
函数必须在设置img.src
之前定义,尝试一下。 - Calvin GodfreyhasError
的值。img.onload
是异步的,这意味着你的代码的其余部分将继续运行,然后当图片加载完成时,onload函数将随后执行。你的问题与图像方向无关,因为你说当图像是横向时它输出true
。 - Reinstate Monica Cellio