今天在写react组件的时候多次用到前端图片的尺寸,就写了工具方法获取图片的尺寸

/**
 * 获取图片的原始尺寸 支持回调和promise
 * @param src
 * @param cb
 */
export const getImageSize = (src: string, cb?: (size: ImageSize) => void) => {
  const oImg = new Image();
  if (cb) {
    oImg.addEventListener('load', function () {
      typeof cb === 'function' &&
        cb({
          width: this.naturalWidth,
          height: this.naturalHeight,
        });
    });
  }

  // 返回一个promise
  const rePro = new Promise((resolve) => {
    oImg.addEventListener('load', function () {
      resolve({
        width: this.naturalWidth,
        height: this.naturalHeight,
      });
    });
  });

  oImg.src = src;
  return rePro;
};

最近发布了一个个人的组件库,欢迎大家来看一下
https://www.npmjs.com/package/react-xs-component

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐