the-front-end-knowledge-you-may-not-know
the-front-end-knowledge-you-may-not-know copied to clipboard
获取图片原始尺寸
let getImgRawSize = (img, cb) => {
img = img || document.querySelector(img)
if (!img instanceof HTMLImageElement) {
return console.log(`error getting ${img} dom`)
}
if (img.naturalWidth) {
return cb({width: img.naturalWidth, height: img.naturalHeight})
}
if (img.complete) {
return cb({width: img.width, height: img.height})
}
let _image = new Image
_image.src = img.src
_image.onload = _ => {
cb({width: _image.width, height: _image.height})
}
}
第一行代码就错了吧。。
之前也写过一篇,不借助ImageElement的 https://github.com/iamgqb/I-should-know/issues/2
其实 onload
事件需要设置在 _image.src = img.src
语句之前
其实
onload
事件需要设置在_image.src = img.src
语句之前
这里js执行比发起网络请求要快,所以不会影响吧。但放到前面会保险一些
如果 image 的width
,height
被设置,是不准确的。
<img src="path.png" width="100" height="100" alt="image" />
or
const image = new Image()
image.width = 100
image.height = 100
image.src = 'path.png'
应该只能依据img.naturalWidth
或者new Image()
来判断
export default function(image: HTMLImageElement) {
return new Promise((resolve, reject) => {
if (image.naturalWidth) {
resolve({ width: image.naturalWidth, height: image.naturalHeight })
}
const savedImage = new Image()
savedImage.onload = () => {
resolve({ width: savedImage.width, height: savedImage.height })
}
savedImage.onerror = err => {
reject(err)
}
savedImage.src = image.src
})
}
img = img || document.querySelector(img)
这句应该是不对的吧。看上去像是支持 DOM 和 选择器,但是其实并不会执行选择器部分。
img = img || document.querySelector('img')
或者是直接删掉?或者是应该判断是img是字符串,然后就去querySelector
@github-linong 是的。 工作两年半后,来更新下代码
function getImgRawSize(img: HTMLImageElement | string): Promise<{ width: number; height: number }> {
const $img: HTMLImageElement = typeof img === 'string' ? document.querySelector(img) : img;
return new Promise((resolve, reject) => {
if ($img.naturalWidth) {
resolve({ width: $img.naturalWidth, height: $img.naturalHeight });
}
if ($img.complete && !$img.getAttribute('width') && !$img.getAttribute('height')) {
resolve({ width: $img.width, height: $img.height });
}
const image = new Image;
image.onload = () => {
resolve({ width: image.width, height: image.height })
}
image.onerror = reject;
image.src = $img.src;
})
}