P5JS绘制无重叠圆形代码无报错但无显示问题排查
问题分析与修复方案
核心问题
你的代码运行后无图形显示,主要是3个逻辑错误导致:
- 背景刷新覆盖图形:
draw()函数持续调用并清空背景,但你只在setup()里执行了一次绘制,刚画的圆立刻被擦掉。 - 重叠检测逻辑混乱:先直接把新圆塞进数组再检测重叠,还错误地在循环里重复添加,同时会和自己比较(距离为0必然判定重叠)。
- 绘制时机错误:单次绘制无法对抗
draw()的持续清屏操作。
修复后的代码
class Particle { constructor(x, y, r) { this.x = x; this.y = y; this.r = r; } show() { noFill(); stroke(0); strokeWeight(1); ellipse(this.x, this.y, this.r); } } let circles = []; function setup() { createCanvas(600, 400); // 确保生成满25个不重叠的圆 while (circles.length < 25) { let x = random(width); let y = random(height); let r = 50; let candidate = new Particle(x, y, r); let overlap = false; // 只和已存在的圆检测重叠 for (let other of circles) { let d = dist(candidate.x, candidate.y, other.x, other.y); // 半径之和(r是直径,所以取一半) if (d < candidate.r/2 + other.r/2) { overlap = true; break; // 有重叠就停止检测,提升效率 } } // 不重叠才加入数组 if (!overlap) { circles.push(candidate); } } } function draw() { background(220); // 每次清屏后重新绘制所有圆 for (let circle of circles) { circle.show(); } }
关键修改说明
- 改用
while循环:确保最终能生成25个不重叠的圆(原for循环可能因重叠导致实际数量不足)。 - 候选圆检测逻辑:先创建候选圆,和已有的所有圆比对,不重叠才加入数组,避免提前污染数组。
- 绘制移至
draw():每次清屏后重新绘制所有圆,保证图形持续显示。 - 提前终止重叠检测:一旦发现重叠就跳出循环,减少不必要的计算。
内容的提问来源于stack exchange,提问作者Jiji
相关产品推荐
相关产品推荐

