获取 naturalWidth
方案为获取 naturalWidth。那么 naturalWidth 和 width 有什么不同?
naturalWidth 标识图片的原始宽高。
width 因为历史问题,标识的其实是 DOM 元素宽高。
因为 img 标签会被图片撑开,所以
在不设置 width 属性时,width == naturalWidth
在设置了 width 属性时,width != naturalWidth
img = new Image()
img.src = 'https://www.lilnong.top/static/img/defaultmatch.png'
var img = "https://www.lilnong.top/static/img/defaultmatch.png"
getImgRawSize(img).then((res)=>{
console.log('res',res)
})
function getImgRawSize(img){
return Promise.resolve(new Promise(function(reslove, reject){
var image = img;
if (image instanceof HTMLImageElement) {
if (image.naturalWidth) return reslove({width: image.naturalWidth, height: _image.naturalHeight})
img = img.src
}
if(typeof img == 'string'){
_image = new Image();
_image.src = img
}
image.onload = _ => reslove({width: image.naturalWidth || image.width, height: image.naturalHeight||image.height})
image.onerror = _ => reject({width: 0, height: 0})
}))
}