【问题标题】:Arranging rectangles in a circle with equal distance将矩形排列成等距的圆
【发布时间】:2021-03-14 10:25:54
【问题描述】:

我正在编写一个渲染思维导图的程序。至此,我已经成功将根节点和围绕它的第一级子节点画成一个圆圈。

这是呈现思维导图节点的代码:

const root = data.find((node) => node.parent === undefined);
const level1 = data.filter((node) => node.parent === root.id);
root.x = 0;
root.y = 0;
root.level = 0;

await addMindMapNode(scene, root);
const radius = 2;
const slice = (2 * Math.PI) / level1.length;
for (let i = 0; i < level1.length; i++) {
    const level1node = level1[i];
    level1node.level = 1;
    const angle = slice * i;
    const x = root.x + radius * Math.cos(angle);
    const y = root.y + radius * Math.sin(angle);
    level1node.x = x;
    level1node.y = y;
    await addMindMapNode(scene, level1node);
}

您可以找到whole program on CodeSandbox

输出如下所示(子节点数量不同,从 1 个子节点到 9 个子节点):

如您所见,根据子节点的数量,中心根节点周围的子节点分布看起来或多或少不均匀且不顺眼,尤其是具有 3、7 或 9 个子节点的情况.

这是因为子节点框的矩形格式。框的中心点之间的距离完全相同,但距离的长度(如下图红线段所示)不同,具体取决于位置:

我必须想办法让红色圆圈部分的大小相等。

所以我的问题是:

如何计算渲染每个紫色框的角度,以使每个框之间的距离看起来相同(即考虑每个框的宽度和高度)?

【问题讨论】:

    标签: javascript math graphics 2d trigonometry


    【解决方案1】:

    好的,这是我的尝试(也有图表!)?:

    所以我注意到问题在于用于生成矩形坐标的计算角度需要稍微移动一些小角度β。比如:

    比我更精通数学的人可能会做得更好,但在我的尝试中,我注意到我可以修改矩形本身生成的角度,给定它的尺寸。喜欢:

    所以,插入它:

      const angle = slice * i;
      // == addition starts here
      const opp_hyp = 60/120;
      const b_prime_degrees = Math.atan(opp_hyp);
      const b_prime = 180 * b_prime_degrees/Math.PI;   // converting to radians
      const x = root.x + (radius * Math.cos(angle-b_prime));
      const y = root.y + (radius * Math.sin(angle-b_prime));
      // == addition ends here
    

    使用它,我得到了 3、7 和 9 的以下结果:

    我不太满意,所以完全一时兴起,我决定尝试那个三角形中的其他角,即180-β

      const angle = slice * i;
      // == addition starts here
      const opp_hyp = 60/120;
      const b_prime_degrees = Math.atan(opp_hyp);
      const new_guy = 180 * (180-b_prime_degrees)/Math.PI;
      const x = root.x + (radius * Math.cos(angle-new_guy));
      const y = root.y + (radius * Math.sin(angle-new_guy));
      // == addition ends here
    

    使用 that,我得到了 3、7 和 9 的以下结果:

    ...有点看起来更好,有点。

    希望有比我知识渊博的人来帮助您给出明确的答案。在那之前,我希望我的尝试至少能帮助你朝着正确的方向前进。

    【讨论】:

    • 酷,感谢您对图表的回答和努力!恐怕还不能接受,因为矩形分布不均匀,但这可能是一个很好的起点。
    • 好的。值得一试。我可能会再试一次。如果是这样,将更新答案。不管怎样,一切顺利
    猜你喜欢
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多