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