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

样式:

js实现动态生成不固定数量的气泡_第1张图片

核心代码:

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})`;
}

你可能感兴趣的:(javascript,前端,开发语言)