【问题标题】:Generate random points within an svg circle area in d3 or javascript在 d3 或 javascript 中生成 svg 圆形区域内的随机点
【发布时间】:2018-11-04 22:10:36
【问题描述】:

我有一个 svg 圆形元素,其坐标属性如下:

<circle id="c1" class="area" cx="440" cy="415" r="75"></circle>

我想使用 javascript 或 d3 在圆元素内生成一些随机点。我考虑了正确的申请方法。我得出的结论是,我可以通过两种方式做到这一点:

  • 只生成n个随机点坐标cx,cy,然后检查每个点是否在svg圆内,如果从它到中心的距离最多为圆元素的半径。

    李>
  • 通过生成点的半径为R * sqrt(random()),θ为random() * 2 * PI,计算cx,cy为r * cos(theta)r * sin(theta)

有更好的方法吗?

【问题讨论】:

  • 取决于您想要的分发类型

标签: javascript d3.js math svg geometry


【解决方案1】:

我正在使用@Joseph O'Rourke 的想法来绘制 1500 分。或者,您可以创建一个圈子并重复使用它。

另外,如果您不需要使用这些点,您可以考虑使用 svg 模式

const SVG_NS = "http://www.w3.org/2000/svg";
let R = 50;
let c = { x: 50, y: 50 };

let g = document.createElementNS(SVG_NS, "g");

for (let i = 0; i < 1500; i++) {
  let a = Math.random() * 2 * Math.PI;// angle
  let r = Math.sqrt(~~(Math.random() * R * R));// distance fron the center of the main circle
  // x and y coordinates of the particle
  let x = c.x + r * Math.cos(a);
  let y = c.y + r * Math.sin(a);
  // draw a particle (circle) and append it to the previously created g element.
  drawCircle({ cx: x, cy: y, r: 1 }, g);
}

function drawCircle(o, parent) {
  var circle = document.createElementNS(SVG_NS, "circle");
  for (var name in o) {
    if (o.hasOwnProperty(name)) {
      circle.setAttributeNS(null, name, o[name]);
    }
  }
  parent.appendChild(circle);
  return circle;
}
//append the g element to the svg
svg.appendChild(g);
svg {
  border: 1px solid; 
  max-width: 90vh;
}
&lt;svg id="svg" viewBox="0 0 100 100"&gt;&lt;/svg&gt;

【讨论】:

  • 两个答案都很棒。但这一个也有一个实际的应用示例场景。谢谢!
【解决方案2】:

您的第二种方法不会在圆圈内产生均匀分布。 请参见下面的左图。

此进程的名称为“disk point-picking”。 请参阅该文章以实现下面的正确图像



图片来自数学世界。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    相关资源
    最近更新 更多