js实现动态生成不固定数量的气泡

样式:

核心代码:

1、添加气泡的方法

addCircle() {
    let height = 645;
    let width = 312;
    let minSize = 38;
    let maxSize = 78;
    let newCircle = {
        x: Math.random() * width, // 随机位置,留出边界
        y: Math.random() * height,
        size: (minSize + Math.random() * (maxSize - minSize + 1)) // 随机大小
    };
    // 检查超出边框,则重新生成
    if ((newCircle.x + newCircle.size * 2 > width) || (newCircle.y + newCircle.size * 2 > height)) {
        return this.addCircle();
    }

    // 检查重叠,如果重叠则重新生成
    let isOverlap = this.circles?.some(item => this.checkOverlap(newCircle, item));
    // 如果重叠,则重新生成新圆
    if (isOverlap) {
        return this.addCircle();
    }
    // 每次生成随机颜色
    let color = this.getRandomHslaColor();
    newCircle.color = color;
    this.circles.push(newCircle);
}

2、校验是否有重叠

checkOverlap(circle1, circle2) {
    // 简单的圆与圆的重叠检测
    let x1 = circle1.x + circle1.size;
    let x2 = circle2.x + circle2.size;
    let y1 = circle1.y + circle1.size;
    let y2 = circle2.y + circle2.size;
    const distance = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
    // +10是为了留出边距
    return distance < circle1.size + circle2.size + 10;
}

3、生成随机颜色

getRandomHslaColor() {
    let h = Math.floor(Math.random() * 360);
    let s = Math.floor(Math.random() * 100) + '%';
    let l = Math.floor(Math.random() * 100) + '%';
    let a = Math.random().toFixed(2); // 生成0.00到1.00之间的透明度值
    return `hsla(${h},${s},${l},${a})`;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值