JS获取图片的宽高

​获取 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})
    }))
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值