javascript - 在 d3 或 javascript 中生成 svg 圆形区域内的随机点
问题描述
我有一个带有坐标属性的svg circle 元素,如下所示:
<circle id="c1" class="area" cx="440" cy="415" r="75"></circle>
我想通过使用 javascript 或 d3 在圆元素内生成一些随机点。我考虑了正确的申请方法。我得出的结论是,我可以通过两种方式做到这一点:
通过仅生成 n 个随机点坐标 cx,cy ,然后检查每个点是否在 svg 圆内,如果从它到中心的距离最多为圆元素的半径。
通过生成点的半径 as
R * sqrt(random())
和 theta asrandom() * 2 * PI
并计算 cx,cy asr * 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>
推荐阅读
- python - 您可以按字母顺序将字典键排序到列表变量中并使用特定输出进行打印吗?
- python - 使用 CouchDB-Python 批量取消删除 CouchDB 文档
- python - 使用 conda 在 Visual Studio python 项目中安装 PyTorch
- python - 当有 None 时打印一些东西
- javascript - Javascript - 如何在 chart.js 的选项规范区域内插入 if 和 else 语句
- json - Oracle JSON 数组查询
- r - 如何使用 R (sjp.frq) 将 y 轴范围从条形图中的数字更改为百分比 (%)
- python-3.x - 将电话字母转换为数字并使用 while 循环
- vue.js - 如何控制vue应用的流量
- c# - 什么会减少此功能中四联骨牌的抖动行为?