首先看一下网页星球钻石页面:

网易星球钻石随机排列且不重叠代码实现

从图片可以看出钻石的排列是随机的且不重叠,那么怎么实现这样的效果呢?代码如下(vue):

1.html部分

<template>
  <div>
    <div>{{randomArr}}</div>
    <div class="my-balls">
      <span class="ball" v-for="(ball,index) in randomArr" :key="index" :style="{left: `${ball.left}px`,top:`${ball.top}px`}">{{ball.left}}-{{ball.top}}</span>
    </div>
  </div>
</template>

2.js部分

<script>
export default {
  data () {
    return {
      clientWidth: document.documentElement.clientWidth,
      randomArr: [],
      maxCount: 8
    }
  },
  created () {
  	this.createdBalls()
  },
  methods: {
    createdBalls () {
      let count = this.maxCount
      const showHeight = 160   //限制钻石生成区域高度
      const showWidth = this.clientWidth - 40
      while (count > 0) {
      	const row = Math.floor(Math.random() * showHeight)
        const col = Math.floor(Math.random() * showWidth)
      	if (this.randomArr.length === 0) {
        	this.randomArr.push({
          	left: col,
            top: row
          })
          count -= 1
        } else {
        	const noOverlap = this.randomArr.every(v => Math.hypot(v.left - col, v.top - row) > 60)  //这里的主要目的就是来保证每次随机生成的点确定的图片位置不会有重叠
          if (noOverlap) {
          	this.randomArr.push({
              left: col,
            	top: row
            })
            count -= 1
          }
        }
      }
    }
  }
}
</script>

3.css部分

<style>
  .my-balls{
    position: relative;
  }
  .ball{
    position: absolute;
    width: 40px;
    height: 40px;
    background: red;
  }
</style>

4.效果实现

网易星球钻石随机排列且不重叠代码实现

 

相关文章:

  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2023-02-26
  • 2021-12-06
  • 2022-01-12
  • 2021-12-02
猜你喜欢
  • 2021-12-21
  • 2021-06-18
  • 2021-07-27
  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
  • 2021-09-04
相关资源
相似解决方案