随机生成多个不重叠圆圈 纯javascript

随机生成多个不重叠圆圈 纯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>

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

翼晗

苦逼三线前端,给点支持吧。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值