react 动态获取图片原始尺寸

940 阅读1分钟

动态获取图片原始尺寸函数

const myHeight=184

const imageSize = (url) => {
    const nImg = new window.Image();
    nImg.src = url;
    return new Promise((resolve, reject) => {
      nImg.onload = () => {
        resolve({ success: true, width: nImg.width, height: nImg.height });
      };
      nImg.onerror = () => {
        reject(new Error('imageError'));
      };
    });
  };
  
  
  useEffect(() => {
    if (!src) return;
    imageSize(src).then((size) => {
      const { width = 0, height = 1 } = size;
      const proportion = height / width; // 移动端基本上是16:9 或者 16:10
      const h = proportion * myHeight;
      const w = myHeight / proportion; //w为根据原始尺寸宽高比,固定高度计算的动态宽度
      if (h < myHeight)) {
       //如图片高度小于需要撑开的高度,则作相应处理
      
      } else {
        //反之。。
      }
    }); // 失败);
  }, [src]);