JavaScript实现固定区域内不重叠随机圆生成算法

作者:页面旅途时间:2026-10-23 12:20:28浏览:539

本文介绍在固定Canvas区域内生成不重叠随机圆的JavaScript实现方案。针对固定半径和随机半径两种场景,分别提供基于碰撞检测的重试机制与基于最近邻距离计算的相切算法。通过示例代码展示如何控制圆的数量、半径范围及边界限制,解决生成失败或重叠问题,适用于数据可视化或界面装饰等前端开发场景。

本文分享一个使用JavaScript在指定区域内生成不重叠随机圆形的示例,供开发者参考。

涉及技术点包括:JavaScript编程、固定绘图区域、圆形不重叠逻辑、以及半径固定或随机生成的策略。

需求背景与问题分析

近期项目中遇到一个具体需求:需要在500x500像素的固定画布区域内绘制10个圆形,要求这些圆形的半径保持一致,且彼此之间不能发生重叠。

当圆形的数量固定且半径也固定时,存在一种可能性,即在某些极端布局下可能无法找到满足所有条件的解。

不过实现难度并不大,关键在于合理控制半径的最大值,以避免因空间不足导致生成失败。

最终生成的视觉效果如下图所示:

需求背景与问题分析

算法实现思路

具体的实现思路如下:

固定半径生成策略

针对固定半径的场景:

步骤1:在指定区域内随机生成一个圆心坐标。\n\n步骤2:设定一个固定半径(策略上建议从大到小尝试固定半径)。\n\n步骤3:验证该圆心和半径是否合法,即检查圆形是否超出画布边界,以及是否与已生成的其他圆形发生相交。\n\n步骤4:如果验证不通过(非法),则重新执行步骤2和步骤3,直到找到合法位置。\n\n步骤5:如果验证通过(合法),则将该圆形记录为新生成的对象。\n\n步骤6:重复执行步骤1至步骤5,直至成功生成10个圆形。

随机半径生成策略

针对随机半径的场景:

步骤1:在指定区域内随机生成一个圆心坐标。\n\n步骤2:根据当前圆心坐标,计算其与所有已存在圆形的最短圆心距,并减去已存在圆的半径(即 最短圆心距 - R_n),以此差值作为新圆的半径。这种策略旨在生成一个与现有圆相切的新圆。\n\n步骤3:验证圆心和半径是否合法,主要检查是否超出画布边界。\n\n步骤4:如果验证不通过(非法),则重新执行步骤2和步骤3。\n\n步骤5:如果验证通过(合法),则将该圆形记录为新生成的对象。\n\n步骤6:重复执行步骤1至步骤5,直至成功生成10个圆形。

具体代码实现如下:

代码实现与配置


// 参数
let obj = {
  id: string, // canvas 的id
  fix:boolean, // 是否固定半径,默认为false
  minMargin: Number, // 两个圆的最短距离,默认为10
  minRadius: Number, 最小的圆半径,默认为30
  radiuArr: Array, 圆的半径的数组,当fix为true时该值必须填
  total: Number ,圆的个数,默认为10
} 

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
class Circle {
  constructor(x, y, r, color){
    this.x = x
    this.y = y
    this.r = r,
    this.c = color ? color : this.getRandomColor()
  }
  getRandomColor(){ 
    let r = Math.floor(Math.random()*100) + 155
    let g = Math.floor(Math.random()*100) + 155
    let b = Math.floor(Math.random()*100) + 155
    return `rgb(${r},${g},${b})` 
  } 
}

class RandomCircle {

  constructor(obj) {
    this.c      = document.getElementById(obj.id);
    this.ctx     = this.c.getContext("2d");
    this.dWidth   = this.c.width;
    this.dHeight   = this.c.height

    this.fix     = obj.fix || false;
    this.minMargin  = obj.minMargin || 10 
    this.minRadius  = obj.minRadius || 30
    this.radiuArr  = obj.radiuArr || [80,70,60,50,45,40,40,35,35,30]
    this.total = obj.total || 10
    this.circleArray = []
    this.circleNumber = 1
  }


  drawOneCircle(c) {
    let ctx = this.ctx;
    ctx.beginPath();
    ctx.strokeStyle = c.c;
    ctx.fillStyle=c.c;
    ctx.arc(c.x, c.y, c.r, 0, 2*Math.PI);
    ctx.stroke();
    ctx.fill();

    ctx.fillStyle='black';
    ctx.fillText('No:'+this.circleNumber, c.x-10, c.y-5);
    ctx.fillText('R:'+c.r, c.x-10, c.y+5);
    this.circleNumber ++ 
  }

  check(x,y,r) {
    return !(x+r > this.dWidth || x-r < 0 || y + r > this.dHeight || y-r < 0)
  }

  // 获取一个新圆的半径,主要判断半径与最近的一个圆的距离
  getR(x,y) {
    if (this.circleArray.length === 0) return Math.floor(Math.random()*20 + 80)
    let lenArr = this.circleArray.map(c => {
      let xSpan = c.x-x
      let ySpan = c.y-y
      return Math.floor(Math.sqrt(Math.pow(xSpan,2) + Math.pow(ySpan,2))) - c.r
    })
    let minCircleLen = Math.min(...lenArr)
    let minC = this.circleArray[lenArr.indexOf(minCircleLen)]
    let tempR = this.fix ? this.radiuArr[this.circleArray.length] : minCircleLen - this.minMargin
    let bool = this.fix ? (tempR <= minCircleLen - minC.r) : (tempR >= this.minRadius)
    return bool ? tempR : false
  }

  // 生成一个圆,随机生成圆心。
  // 如果连续生成200次半径都没有合适的话,终止进程
  createOneCircle(){
    let x,y,r;
    let createCircleTimes = 0
    while(true) {
      createCircleTimes ++ 
      x = Math.floor(Math.random()*this.dWidth)
      y = Math.floor(Math.random()*this.dHeight)
      let TR = this.getR(x,y)
      if (!TR) {
        continue;
      } else {
        r = TR
      }
      if (this.check(x,y,r) || createCircleTimes > 200) {
        break
      }

    }
    this.check(x,y,r) && this.circleArray.push(new Circle(x, y, r))

  }

  // 如果生成100次新圆都失败的话,终止方案。
  // 如果生成100种方案都没有合适可用的话,终止进程。
  init() {
    let n = 0
    while(this.circleArray.length < this.total) {
      this.circleArray = []
      let i = 0;
      while (this.circleArray.length < this.total) {
        this.createOneCircle()
        i ++ 
        if (i >= 100) {
          break;
        }
      }
      n ++ 
      if (n > 100) {
        break;
      }
    }
    // 根据半径从大到小画圆。
    this.circleArray.sort( (a,b) => b.r-a.r).forEach(c => {
      this.drawOneCircle(c)
    })
  }
}


let p = new RandomCircle({id: 'myCanvas', total: 20})
p.init()

console.log(p.circleArray)

</script> 
</body>
</html>

以上就是本文的全部内容,希望能为各位的学习提供有益的帮助,同时也欢迎大家继续支持本站。

作者最新文章