javascript - 在 d3 或 javascript 中的 svg 圆区域内生成随机点

标签 javascript d3.js math svg geometry

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

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

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

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

    <
  • 通过生成点的半径 R * sqrt(random()) 和 theta 作为 random() * 2 * PI 并计算 cx ,cy 作为 r * cos(theta)r * sin(theta)

有没有更好的方法?

最佳答案

我正在使用@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;
}
<svg id="svg" viewBox="0 0 100 100"></svg>

关于javascript - 在 d3 或 javascript 中的 svg 圆区域内生成随机点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146015/

相关文章:

java - 时空权衡

java - 如何将奇数索引转换为索引 {0,1,2,3,4,5}?

svg - 通过画刷在 d3 中绘制散点图的焦点+上下文

javascript - D3 - 将事件添加到酒吧

javascript - 在D3中如何为当前特定路径启用鼠标悬停事件?

javascript - jQuery,动画仅适用于 1 张图像

haskell - 在 haskell 中创建一个返回该类型类的另一个实例的类型类

javascript - 单击时更改 div 的背景图像

javascript - 如何让工具提示悬停在文本框上方?

javascript - jQuery:使用动态生成变量作为选择器将 JSON 输入附加为内容