随机生成多个不重叠圆圈 纯javascript
<template>
<div
class="wrapper"
:style="{ width: width + 'px', height: height + 'px' }"
>
<div
class="circle"
v-for="item in pos"
:style="{
left: item.x + 'px',
top: item.y + 'px',
width: item.width + 'px',
height: item.height + 'px',
}"
></div>
</div>
</template>
<script setup name="circles" lang="ts">
import { onMounted } from "vue";
// 总的宽高
let width = 1920;
let height = 1080;
// 每个模块的最大,最小宽度(因为画圆,所以宽高一致,割出来的是正方形)
let minr = 40;
let minR = 120;
let maxR = 150;
let leave = 0;
onMounted(() => {
getColWS();
});
let colWS = [];
let pos = ref([]);
function getColWS() {
let len = 0;
while (len < width - maxR) {
let w = Math.floor(Math.random() * (maxR - minR) + minR);
colWS.push(w);
len += w + Math.random() * 5;
leave = width - len;
}
colWS.push(leave);
getPosition();
}
function getPosition() {
let x = 0;
colWS.forEach((col) => {
let y = 0;
while (y <= height - 10) {
let h = Math.floor(Math.random() * (col - minr) + minr);
if (y + h > height) {
h = height - y;
}
if (h >= minr) {
let rate = Math.floor(col / h);
for (let i = 0; i < rate; i++) {
let p = getCirclePosition({
x: x + (i * col) / rate,
y: y,
width: h,
height: h,
});
pos.value.push({
x: p.x,
y: p.y,
width: p.r,
height: p.r,
});
}
}
y += h + Math.random() * 5;
}
x += col;
});
}
function getCirclePosition(item) {
let r = Math.random() * (item.height - minr) + minr;
let x = item.x + Math.random() * (item.width - r);
let y = item.y + Math.random() * (item.width - r);
return { x, y, r };
}
</script>
<style lang="scss" scoped>
.wrapper {
width: 960px;
height: 540px;
border: 1px solid red;
position: relative;
.canvas {
width: 100%;
height: 100%;
}
.circle {
position: absolute;
border: 1px solid red;
border-radius: 50%;
}
}
</style>