You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在p5.js中让圆形阵列显示在平行四边形边界内

实现思路
  • 核心逻辑是先判断随机生成的圆心坐标是否落在平行四边形内部,只有符合条件的坐标才会被用来创建圆形
  • 这里用射线法实现多边形内部点判断:从目标点向右发射一条水平射线,统计射线和多边形边的交点数量,奇数表示点在内部,偶数表示在外部,该方法支持任意不规则多边形的内点检测。
修改后的完整代码
let circles = [];
// 提前定义平行四边形顶点,统一维护边界参数
const quadVertices = [[400,600],[800,200],[800,600],[400,1000]];

function setup() {
  createCanvas(1200, 1200);
  colorMode(HSB,360,100,100,1);
  
  for (let i = 0; i < 500; i++) {
    // 随机范围覆盖平行四边形的最大外接矩形,提高命中效率
    let x = random(400, 800);
    let y = random(200, 1000);
    // 仅当坐标落在平行四边形内时才创建圆形
    if (pointInPoly(x, y, quadVertices)) {
      let d = 10;
      circles.push(new circleClass(x, y, d));
    } else {
      // 不符合条件则重试当前次,保证最终生成500个有效圆形
      i--;
    }
  }
}

function draw() {
  background(35,13,90,1);
  noLoop();

  for (let i = 0; i < circles.length; i++) {
    circles[i].show();
  }
  
  noFill();
  stroke(0);
  // 直接使用预定义顶点绘制边界,避免参数不一致
  quad(...quadVertices.flat());
}

class circleClass {
  constructor(x, y, d) {
    this.x = x;
    this.y = y;
    this.d = d;
  }
  show() {
    noStroke();
    fill(27, 71, 73, 1);
    ellipse(this.x, this.y, this.d);
  }
}

// 射线法判断点是否在多边形内部
function pointInPoly(px, py, vertices) {
  let inside = false;
  for (let i = 0, j = vertices.length - 1; i < vertices.length; j = i++) {
    const [xi, yi] = vertices[i];
    const [xj, yj] = vertices[j];
    // 判断射线是否和当前边相交
    const intersect = ((yi > py) != (yj > py))
        && (px < (xj - xi) * (py - yi) / (yj - yi) + xi);
    if (intersect) inside = !inside;
  }
  return inside;
}
扩展说明

如果需要保证整个圆形完全不超出平行四边形边界,仅判断圆心不够,还需要额外计算圆心到平行四边形四条边的距离都大于等于圆的半径即可。

内容的提问来源于stack exchange,提问作者astromango

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:45:04