vue 固定范围内随机位置生成 图片(可其他东西)
先说一下思路:
- 在一个范围内(主要是为了确认随机生成的图片中心点在范围内)
- 拿到图片半径(可随机,看需求)
- 随机生成xy坐标 (left,top)
- 第一个判断:判断是否在规定范围内
x (随机点的X) - r (半径) >=0 && y(随机点的Y)-r>=0
x+r<= W(范围宽) && y+r<=H (范围高) - 判断最新生成的 图片 范围内是否 有其他的图片
假设我们生成的图片集合成一个 list:[{x:150,y:90,r:30},{x:240,y:70,r:30}…]
最新的 图片:x: 260,y: 140,r:60
for(var i in list){
if(list[i].x>=260&&list[i].x<=260+2*60){
return false
}
if(list[i].y>=260&&list[i].y<=260+2*60){
return false
}
}
如果没有返回false,就把他丢到 list里面,即又生成一个。
开始实现
html
<div class="component" :style="`width:${clientWidth}px;height:${clientHeight}px;`">
<template v-for="(item,index) in graphicsList">
<div class="graphics" :key="index" :style="`left:${item.x}px;top:${item.y}px;`">
<img src="">
</div>
</template>
</div>
js
data() {
return {
clientHeight: null,
clientWidth: null,
// 半径 即图片100*100
radius: 50, // 有随机要求可动态生成
graphicsList:[]
};
},
methods: {
// 获取可视区域
getClient(){
// 获取html可视区域高度
this.clientHeight = document.documentElement.clientHeight - 100 // 预留100px不紧贴屏幕
this.clientWidth = document.documentElement.clientWidth - 120 // 预留120px不紧贴屏幕
},
// 随机生成图形位置(xy坐标)
generateLocation(){
let x = Math.floor(Math.random()*this.clientHeight) + this.radius // 加 this.radius 保证图形中心在范围内,后面可少判断一步
let y = Math.floor(Math.random()*this.clientWidth) + this.radius
return {
x,
y,
r: this.radius
}
},
// 生成
generate(){
let obj = this.generateLocation()
// 判断是否在规定范围内
if(obj.x + obj.r>this.clientHeight){
return false
}
if(obj.y + obj.r>this.clientHeight){
return false
}
// 判断最新生成的 图片 范围内是否 有其他的图片
if(this.graphicsList.length!==0){
for(var i in list){
// 判断是否在规定范围内
if(list[i].x>= obj.x && list[i].x<= obj.x + (obj.r*2)){
return false
}
if(list[i].y>= obj.x && list[i].y<= obj.x + (obj.r*2)){
return false
}
if(Number(i)+1==list.length){
this.graphicsList.push(obj)
}
}
}else{
this.graphicsList.push(obj)
}
},
},
scss
.component {
position: absolute;
.demo {
width: 100px;
height: 100px;
position: absolute;
z-index: 2;
img {
position: relative;
object-fit: contain;
width: 100px;
height: 100px;
}
}
}