APP 需要做一个类似蚂蚁森林的功能模块,动效和蚂蚁森林接近,可以有多个水滴,可以控制位置,水滴上下浮动。
gif图如下所示:
<!-- 布局代码块 -->
<div class="main_contain" ref="userinfo" id="userinfo">
<template>
<div
v-for="(item, index) in ballList"
:key="index"
class="ball_small"
:style="{
top: all_y[index] + 'px',
left: all_x[index] + 'px',
transition: 'all 2s',
backgroundImage:
'url(' + sbg[Math.round(Math.random() * (2 - 0) + 0)].url + ')',
backgroundSize: '100% 100%'
}"
>
<img src="@images/index/i2.png" alt="" /> <!-- 小球中的图标 -->
<p>1000</p>
</div>
</template>
</div>
data() {
return {
ballList: [0,1,2,3,4,5,6,7,8,9,10],//后台返回的小球信息
sbg: [
{
url: require("@images/index/bor.png")
},
{
url: require("@images/index/bor2.png")
},
{
url: require("@images/index/bor3.png")
}
],//小球背景图
xStart: 0,
yStart: 0,
jsonArr: [],
all_x: [],
all_y: [],
};
},
mounted() {
this.getQiu(this.ballList.length);//小球个数
for (let i = 0; i < this.jsonArr.length; i++) {
this.all_x.push(this.jsonArr[i].xStart);
this.all_y.push(this.jsonArr[i].yStart);
}
},
getQiu(number) {
let iconWidth = 60; //值越大,元素左右间隔越大
let iconHeight = 60; //值越大,元素上下间隔越大
let targetHeight = this.$refs.userinfo.offsetHeight;
let targetWidth = this.$refs.userinfo.offsetWidth;
let _tmpArray = [];
let num = number;
if (targetWidth < iconWidth || targetHeight < iconHeight) {
return false;
}
var xNum = parseInt(targetWidth / iconWidth, 10); //用浏览器的宽度除以一个元素的宽度可算出浏览器窗口内一行可以放置元素的个数
var yNum = parseInt(targetHeight / iconHeight, 10); //用浏览器的高度除以一个元素的高度可算出浏览器窗口内一列可以放置元素的个数
var allNum = xNum * yNum; //浏览器窗口内总共可以放置元素的个数
console.log(allNum);
//当需要放置的元素的个数超过浏览器窗口内总共可以放置的元素的个数时,则返回
if (num >= allNum) {
return false;
}
for (var i = 0; i < allNum; i++) {
_tmpArray.push(i);
}
while (num) {
var pointer = Math.floor(Math.random() * allNum); //向下取整取出0到allnum之间的任意一个整数
if (!_tmpArray[pointer]) {
continue;
}
delete _tmpArray[pointer]; //删除数组_tmpArray中第pointer个值
this.yStart = parseInt(pointer / xNum, 10) * iconWidth;
this.xStart = (pointer % xNum) * iconHeight;
this.jsonArr.push({
xStart: this.xStart,
yStart: this.yStart
});
num--;
}
}