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

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

从图片可以看出钻石的排列是随机的且不重叠,那么怎么实现这样的效果呢?代码如下(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.效果实现

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值