在前端获取加载图片的宽度和高度
有时候后端那边无法给出图片的宽高,因此只能在前端加载图片的时候,获取图片的宽高。
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取加载图片的信息</title>
</head>
<body>
<script>
function getImgInfo(imgUrl) {
return new Promise((resolve, reject) => {
let img = new Image()
let obj = {}
// 图片加载成功
img.onload = function () {
obj = {
width: this.width,
height: this.height,
}
resolve(obj)
}
// 图片加载失败
img.onerror = function() {
console.log('img load error')
};
img.src = imgUrl
})
}
getImgInfo('https://img2022.cnblogs.com/blog/1053464/202206/1053464-20220606150500511-73127963.jpg').then((res) => {
console.log('success ', res)
})
</script>
</body>
</html>