其他分享
首页 > 其他分享> > vue宫格图片

vue宫格图片

作者:互联网

vue实现一个根据图片大小自定义生成的多宫格图组件,新年将近,它来了

 <!-- 有过渡动画的出现 -->
  <transition-group
    tag="div"
    name="el-zoom-in-center"
    duration="2000"
    class="Gonggetu"
    :style="{
      width: boxwidth + 'px',
      height: boxheight + 'px',
      overflow: 'hidden',
    }"
  >
    <div
      class="flypicture"
      :style="{
        background: 'url(' + HttpsUrl + ') ' + item.Iwidth + ' ' + item.Iheight,
      }"
      v-for="(item, index) in album"
      :key="index"
    ></div>
  </transition-group>

JS代码

data() {
    return {
      imgWH: 100, // 分割小块初始宽高
      rows: "", // 横向数
      columns: "", // 竖向数
      album: [], // 存放小块位置的数组
      Iboxwidth: "", // 暂存原图宽
      Iboxheight: "", // 暂存原图高
    };
  },
  //接收
  props: {
    getImg: String, // 接收的网络图片地址,使用本地图片转Base64时显示存在问题,后续更新
  },
  computed: {
    // 图片地址( 默认图程序猴泡温泉)
    HttpsUrl() {
      return (
        this.getImg ||
        "https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg"
      );
    },
    //计算带有边框的容器宽
    boxwidth() {
      return this.Iboxwidth + this.rows;
    },
    //计算带有边框的容器高
    boxheight() {
      return this.Iboxheight + this.columns;
    },
  },
  methods: {
    photograph() {
      let that = this;
      // 借助Image对象
      var img_url = this.HttpsUrl;
      var img = new Image();
      img.src = img_url;
      // 通过计时器获取原图的宽高
      let setImg = setInterval(() => {
        if (img.width > 0) {
          // 拿到原图信息关闭计时器
          clearInterval(setImg);
          // 暂存一下图片宽高
          that.Iboxwidth = img.width;
          that.Iboxheight = img.height;
          //计算
          that.rows = Math.ceil(img.width / that.imgWH); // 计算出原图宽除去小块宽得出的个数
          that.columns = Math.ceil(img.height / that.imgWH); // 计算出原图高除去小块高得出的个数
          that.handle();
        }
      }, 100);
    },
    handle() {
      let that = this;
      // 竖向小块个数在外层
      for (let h = 0; h < this.columns; h++) {
        // 横向小块个数
        for (let w = 0; w < this.rows; w++) {
          // 组成带有坐标的'块'数组用于页面展示
          that.album.push({
            Iwidth: -w * that.imgWH + "px",
            Iheight: -h * that.imgWH + "px",
          });
        }
      }
    },
  },
  mounted() {
    this.photograph();
  },

css

<style lang="scss" scoped>
.Gonggetu {
  display: flex;
  flex-wrap: wrap;
  .flypicture {
    width: 100px;
    height: 100px;
    border-left: 1px solid #fff;
    border-top: 1px solid #fff;
  }
}
</style>

真的-----毫无保留,哈哈,不信你看效果图
在这里插入图片描述
点个赞呗,快乐多一点

标签:原图,vue,imgWH,img,width,let,宫格,columns,图片
来源: https://blog.csdn.net/Key_Val/article/details/112904896