将一堆图片自适应页面排列

更新日期: 2020-05-02阅读: 1.6k标签: 自适应

最近在开发一个批量展示图片的页面,图片的自适应排列是一个无法避免的问题

在付出了许多头发的代价之后,终于完成了图片排列,并封装成组件,最终效果如下



一、设计思路

为了使结构清晰,我将图片列表处理成了二维数组,第一维为行,第二维为列

render() {
    const { className } = this.props;
    // imgs 为处理后的图片数据,二维数组
    const { imgs } = this.state;

    return (
      <div
        ref={ref => (this.containerRef = ref)}
        className={className ? `w-image-list ${className}` : 'w-image-list'}
      >
        {Array.isArray(imgs) &&
          imgs.map((row, i) => {
            return ( // 渲染行
              <div key={`image-row-${i}`} className="w-image-row">
                {Array.isArray(row) &&
                  row.map((item, index) => {
                    return ( // 渲染列
                      <div
                        key={`image-${i}-${index}`}
                        className="w-image-item"
                        style={{
                          height: `${item.height}px`,
                          width: `${item.width}px`,
                        }}
                        onClick={() => {
                          this.handleSelect(item);
                        }}
                      >
                        <img src={item.url} alt={item.title} />
                      </div>
                    );
                  })}
              </div>
            );
          })}
      </div>
    );
  }

每一行的总宽度不能超过容器本身的宽度,当前行如果剩余宽度足够,就可以追加新图片

而这就需要算出图片等比缩放后的宽度 imgWidth,前提条件是知道图片的原始宽高缩放后的高度 imgHeight

通过接口获取到图片列表的时候,至少是有图片链接 url 的,通过 url 我们就能获取到图片的宽高

如果后端的同事更贴心一点,直接就返回了图片宽高,就想当优秀了

获取到图片的原始宽高之后,可以先预设一个图片高度 imgHeight 作为基准值,然后算出等比缩放之后的图片宽度

const imgWidth = Math.floor(item.width * imgHeight / item.height);

然后将单个图片通过递归的形式放到每一行进行校验,如果当前行能放得下,就放在当前行,否则判断下一行,或者直接开启新的一行


二、数据结构

整体的方案设计好了之后,就可以确定最终处理好的图片数据应该是这样的:

const list = [
  [
    {id: String, width: Number, height: Number, title: String, url: String},
    {id: String, width: Number, height: Number, title: String, url: String},
  ],[
    {id: String, width: Number, height: Number, title: String, url: String},
    {id: String, width: Number, height: Number, title: String, url: String},
  ]
]

不过为了方便计算每一行的总宽度,并在剩余宽度不足时提前完成当前行的排列,所以在计算的过程中,这样的数据结构更合适:

const rows = [
  {
    img: [], // 图片信息,最终只保留该字段
    total: 0, // 总宽度
    over: false, // 当前行是否完成排列
  },
  {
    img: [],
    total: 0,
    over: false,
  }
]

最后只需要将 rows 中的 img 提出来,生成二维数组 list 即可 

基础数据结构明确了之后,接下来先写一个给新增行添加默认值的基础函数

// 以函数的形式处理图片列表默认值
const defaultRow = () => ({
  img: [], // 图片信息,最终只保留该字段
  total: 0, // 总宽度
  over: false, // 当前行是否完成
});

为什么会采用函数的形式添加默认值呢?其实这和 vue 的 data 为什么会采用函数是一个道理

如果直接定义一个纯粹的对象作为默认值,会让所有的行数据都共享引用同一个数据对象

而通过 defaultRow 函数,每次创建一个新实例后,会返回一个全新副本数据对象,就不会有共同引用的问题


三、向当前行追加图片

我设置了一个缓冲值,假如当前行的总宽度与容器宽度(每行的宽度上限)的差值在缓冲值之内,这一行就没法再继续添加图片,可以直接将当前行的状态标记为“已完成”

const BUFFER = 30; // 单行宽度缓冲值

然后是将图片放到行里面的函数,分为两部分:递归判断是否将图片放到哪一行,将图片添加到对应行

/**
 * 向某一行追加图片
 * @param {Array}  list 列表
 * @param {Object} img 图片数据
 * @param {Number} row 当前行 index
 * @param {Number} max 单行最大宽度
 */
function addImgToRow(list, img, row, max) {
  if (!list[row]) {
    // 新增一行
    list[row] = defaultRow();
  }
  const total = list[row].total;
  const innerList = JSON.parse(JSON.stringify(list));
  innerList[row].img.push(img);
  innerList[row].total = total + img.width;
  // 当前行若空隙小于缓冲值,则不再补图
  if (max - innerList[row].total < BUFFER) {
    innerList[row].over = true;
  }
  return innerList;
}

/**
 * 递归添加图片
 * @param {Array} list 列表
 * @param {Number} row 当前行 index
 * @param {Objcet} opt 补充参数
 */
function pushImg(list, row, opt) {
  const { maxWidth, item } = opt;
  if (!list[row]) {
    list[row] = defaultRow();
  }
  const total = list[row].total; // 当前行的总宽度
  if (!list[row].over && item.width + total < maxWidth + BUFFER) {
    // 宽度足够时,向当前行追加图片
    return addImgToRow(list, item, row, maxWidth);
  } else {
    // 宽度不足,判断下一行
    return pushImg(list, row + 1, opt);
  }
}


四、处理图片数据

大部分的准备工作已经完成,可以试着处理图片数据了

constructor(props) {
  super(props);
  this.containerRef = null;
  this.imgHeight = this.props.imgHeight || 200;
  this.state = {
    imgs: null,
  };
}
componentDidMount() {
  const { list = mock } = this.props;
  console.time('CalcWidth');
  // 在构造函数 constructor 中定义 this.containerRef = null;
  const imgs = this.calcWidth(list, this.containerRef.clientWidth, this.imgHeight);
  console.timeEnd('CalcWidth');
  this.setState({ imgs });
}

处理图片的主函数

/**
 * 处理数据,根据图片宽度生成二维数组
 * @param {Array} list 数据集
 * @param {Number} maxWidth 单行最大宽度,通常为容器宽度
 * @param {Number} imgHeight 每行的基准高度,根据这个高度算出图片宽度,最终为对齐图片,高度会有浮动
 * @param {Boolean} deal 是否处理异常数据,默认处理
 * @return {Array} 二维数组,按行保存图片宽度
 */
calcWidth(list, maxWidth, imgHeight, deal = true) {
  if (!Array.isArray(list) || !maxWidth) {
    return;
  }
  const innerList = JSON.parse(JSON.stringify(list));
  const remaindArr = []; // 兼容不含宽高的数据
  let allRow = [defaultRow()]; // 初始化第一行

  for (const item of innerList) {

    // 处理不含宽高的数据,统一延后处理
    if (!item.height || !item.width) {
      remaindArr.push(item);
      continue;
    }
    const imgWidth = Math.floor(item.width * imgHeight / item.height);
    item.width = imgWidth;
    item.height = imgHeight;
    // 单图成行
    if (imgWidth >= maxWidth) {
      allRow = addImgToRow(allRow, item, allRow.length, maxWidth);
      continue;
    }
    // 递归处理当前图片
    allRow = pushImg(allRow, 0, { maxWidth, item });
  }
  console.log('allRow======>', maxWidth, allRow);
  // 处理异常数据
  deal && this.initRemaindImg(remaindArr);
  return buildImgList(allRow, maxWidth);
}

主函数 calcWidth 的最后两行,首先处理了没有原始宽高的异常数据(下一部分细讲),然后将带有行信息的图片数据处理为二维数组

递归之后的图片数据按行保存,但每一行的总宽度都和实际容器的宽度有出入,如果直接使用当前的图片宽高,会导致每一行参差不齐

所以需要使用 buildImgList 来整理图片,主要作用有两个,第一个作用是将图片数据处理为上面提到的二维数组函数

第二个作用则是用容器的宽度来重新计算图片高宽,让图片能够对齐容器:

// 提取图片列表
function buildImgList(list, max) {
  const res = [];
  Array.isArray(list) &&
    list.map(row => {
      res.push(alignImgRow(row.img, (max / row.total).toFixed(2)));
    });
  return res;
}

// 调整单行高度以左右对齐
function alignImgRow(arr, coeff) {
  if (!Array.isArray(arr)) {
    return arr;
  }
  const coe = +coeff; // 宽高缩放系数
  return arr.map(x => {
    return {
      ...x,
      width: x.width * coe,
      height: x.height * coe,
    };
  });
}


五、处理没有原始宽高的图片

上面处理图片的主函数 calcWidth 在遍历数据的过程中,将没有原始宽高的数据单独记录了下来,放到最后处理

对于这一部分数据,首先需要根据图片的 url 获取到图片的宽高

// 根据 url 获取图片宽高
function checkImgWidth(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();

    img.onload = function() {
      const res = {
        width: this.width,
        height: this.height,
      };
      resolve(res);
    };
    img.src = url;
  });
}

需要注意的是,这个过程是异步的,所以我没有将这部分数据和上面的图片数据一起处理

而是当所有图片宽高都查询到之后,额外处理这部分数据,并将结果拼接到之前的图片后面

// 处理没有宽高信息的图片数据
initRemaindImg(list) {
  const arr = []; // 获取到宽高之后的数据
  let count = 0;
  list && list.map(x => {
    checkImgWidth(x.url).then(res => {
      count++;
      arr.push({ ...x,  ...res })
      if (count === list.length) {
        const { imgs } = this.state;
        // 为防止数据异常导致死循环,本次 calcWidth 不再处理错误数据
        const imgs2 = this.calcWidth(arr, this.containerRef.clientWidth - 10, this.imgHeight, false);
        this.setState({ imgs: imgs.concat(imgs2) });
      }
    })
  })
}


六、完整代码

import react from 'react';

const BUFFER = 30; // 单行宽度缓冲值

// 以函数的形式处理图片列表默认值
const defaultRow = () => ({
  img: [], // 图片信息,最终只保留该字段
  total: 0, // 总宽度
  over: false, // 当前行是否完成
});

/**
 * 向某一行追加图片
 * @param {Array}  list 列表
 * @param {Object} img 图片数据
 * @param {Number} row 当前行 index
 * @param {Number} max 单行最大宽度
 */
function addImgToRow(list, img, row, max) {
  if (!list[row]) {
    // 新增一行
    list[row] = defaultRow();
  }
  const total = list[row].total;
  const innerList = JSON.parse(JSON.stringify(list));
  innerList[row].img.push(img);
  innerList[row].total = total + img.width;
  // 当前行若空隙小于缓冲值,则不再补图
  if (max - innerList[row].total < BUFFER) {
    innerList[row].over = true;
  }
  return innerList;
}

/**
 * 递归添加图片
 * @param {Array} list 列表
 * @param {Number} row 当前行 index
 * @param {Objcet} opt 补充参数
 */
function pushImg(list, row, opt) {
  const { maxWidth, item } = opt;
  if (!list[row]) {
    list[row] = defaultRow();
  }
  const total = list[row].total; // 当前行的总宽度
  if (!list[row].over && item.width + total < maxWidth + BUFFER) {
    // 宽度足够时,向当前行追加图片
    return addImgToRow(list, item, row, maxWidth);
  } else {
    // 宽度不足,判断下一行
    return pushImg(list, row + 1, opt);
  }
}

// 提取图片列表
function buildImgList(list, max) {
  const res = [];
  Array.isArray(list) &&
    list.map(row => {
      res.push(alignImgRow(row.img, (max / row.total).toFixed(2)));
    });
  return res;
}

// 调整单行高度以左右对齐
function alignImgRow(arr, coeff) {
  if (!Array.isArray(arr)) {
    return arr;
  }
  const coe = +coeff; // 宽高缩放系数
  return arr.map(x => {
    return {
      ...x,
      width: x.width * coe,
      height: x.height * coe,
    };
  });
}

// 根据 url 获取图片宽高
function checkImgWidth(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();

    img.onload = function() {
      const res = {
        width: this.width,
        height: this.height,
      };
      resolve(res);
    };
    img.src = url;
  });
}

export default class ImageList extends React.Component {
constructor(props) {
  super(props);
  this.containerRef = null;
  this.imgHeight = this.props.imgHeight || 200;
  this.state = {
    imgs: null,
  };
}
componentDidMount() {
  const { list } = this.props;
  console.time('CalcWidth');
  // 在构造函数 constructor 中定义 this.containerRef = null;
  const imgs = this.calcWidth(list, this.containerRef.clientWidth, this.imgHeight);
  console.timeEnd('CalcWidth');
  this.setState({ imgs });
}

/**
 * 处理数据,根据图片宽度生成二维数组
 * @param {Array} list 数据集
 * @param {Number} maxWidth 单行最大宽度,通常为容器宽度
 * @param {Number} imgHeight 每行的基准高度,根据这个高度算出图片宽度,最终为对齐图片,高度会有浮动
 * @param {Boolean} deal 是否处理异常数据,默认处理
 * @return {Array} 二维数组,按行保存图片宽度
 */
calcWidth(list, maxWidth, imgHeight, deal = true) {
  if (!Array.isArray(list) || !maxWidth) {
    return;
  }
  const innerList = JSON.parse(JSON.stringify(list));
  const remaindArr = []; // 兼容不含宽高的数据
  let allRow = [defaultRow()]; // 初始化第一行

  for (const item of innerList) {

    // 处理不含宽高的数据,统一延后处理
    if (!item.height || !item.width) {
      remaindArr.push(item);
      continue;
    }
    const imgWidth = Math.floor(item.width * imgHeight / item.height);
    item.width = imgWidth;
    item.height = imgHeight;
    // 单图成行
    if (imgWidth >= maxWidth) {
      allRow = addImgToRow(allRow, item, allRow.length, maxWidth);
      continue;
    }
    // 递归处理当前图片
    allRow = pushImg(allRow, 0, { maxWidth, item });
  }
  console.log('allRow======>', maxWidth, allRow);
  // 处理异常数据
  deal && this.initRemaindImg(remaindArr);
  return buildImgList(allRow, maxWidth);
}

// 处理没有宽高信息的图片数据
initRemaindImg(list) {
  const arr = []; // 获取到宽高之后的数据
  let count = 0;
  list && list.map(x => {
    checkImgWidth(x.url).then(res => {
      count++;
      arr.push({ ...x,  ...res })
      if (count === list.length) {
        const { imgs } = this.state;
        // 为防止数据异常导致死循环,本次 calcWidth 不再处理错误数据
        const imgs2 = this.calcWidth(arr, this.containerRef.clientWidth - 10, this.imgHeight, false);
        this.setState({ imgs: imgs.concat(imgs2) });
      }
    })
  })
}

  handleSelect = item => {
    console.log('handleSelect', item);
  };

  render() {
    const { className } = this.props;
    // imgs 为处理后的图片数据,二维数组
    const { imgs } = this.state;

    return (
      <div
        ref={ref => (this.containerRef = ref)}
        className={className ? `w-image-list ${className}` : 'w-image-list'}
      >
        {Array.isArray(imgs) &&
          imgs.map((row, i) => {
            return ( // 渲染行
              <div key={`image-row-${i}`} className="w-image-row">
                {Array.isArray(row) &&
                  row.map((item, index) => {
                    return ( // 渲染列
                      <div
                        key={`image-${i}-${index}`}
                        className="w-image-item"
                        style={{
                          height: `${item.height}px`,
                          width: `${item.width}px`,
                        }}
                        onClick={() => {
                          this.handleSelect(item);
                        }}
                      >
                        <img src={item.url} alt={item.title} />
                      </div>
                    );
                  })}
              </div>
            );
          })}
      </div>
    );
  }
}

PS: 记得给每个图片 item 添加样式 box-sizing: border-box;

来自:https://www.cnblogs.com/wisewrong/p/12890769.html

链接: https://www.fly63.com/article/detial/9243

html中map area 热区自适应的原生js实现方案

在做自适应网页的时候,如果在图片中使用了热区map。图片可以通过样式实现:图片大小随页面变化,MAP中每个area的坐标也随页面等比例的变化效果。根据分辨率自适应热区坐标

WKWebView加载的网页自适应大小

有时候在WKWebView加载页面后会发现页面的字会很小, 这是因为原网页没有做手机屏幕尺寸的适配, 那么在后台不做调整的情况下我们移动端怎样来适配页面呢?以下代码可以适配大小

iframe 自适应高度的多种实现方式

实现 iframe 的自适应高度,使其等于内嵌网页的高度,从而看不出来滚动条和嵌套痕迹。对于用户体验和网站美观起着重要作用。 如果内容是固定的,那么我们可以通过CSS来给它直接定义一个高度,同样可以实现上面的需求。

移动端自适应

js动态设置html的字体大小,设计稿宽度750px,设备宽度350px,此时HTML 的font-size:50px,及1rem=50px;设置html的font-size: 13.33vw,设置html的font-size并缩放页面

HTML+Css让网页自动适应电脑手机屏幕

在网页的<head>中增加以上这句话,可以让网页的宽度自动适应手机屏幕的宽度,其中:width=device-width :表示宽度是设备屏幕的宽度,height=device-height :表示宽度是设备屏幕的宽度

CSS实现自适应正方形、等宽高比矩形

利用vw、vh、vmin、vmax,vw表示的是viewport的宽度,也就是视口的宽度,vh表示的是视口的高度;利用双层嵌套来写,将外层的div的position设置relative,内层的position设置为absoult

echarts 表格自适应需要注意的问题

最近在做大屏可视化,页面数据展示基本都是用百度的echarts,因为页面要做自适应,所以当视窗变化的时候echarts也要变化。window.onresize 可以解决这个问题。而一般一个页面不可能只引用一个表格,当你引用多个的时候,有些地方需要注意。

css弹性盒模型实现元素宽度(高度)自适应

css实现左侧宽度固定右侧宽度自适应:定位、浮动、margin;css3弹性盒模型实现自适应:上下高度固定中间高度自适应、左侧宽度固定右侧宽度自适应

web页面实现等比例缩放自适应 - 通过 rem 和 vw 实现

rem 是相对长度单位,是指相对于根元素(即html元素)font-size(字号大小)的倍数;vw 是相对长度单位,相对于浏览器窗口的宽度,浏览器窗口宽度被均分为100个单位的vw,rem 和 vw 结合实现WEB页面等比例缩放自适应

vuejs中拖动改变元素宽度实现宽度自适应大小

拖动效果的实现基本都是dom操作来实现的,通过拖动分隔线,计算分隔线与浏览器边框的距离(left),来实现拖动之后的不同宽度的计算;当拖动分隔线1时,计算元素框left和mid;当拖动分隔线2时

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!