将d3力导向图的节点包围在圆形或多边形或云中

时间:2012-10-15 04:21:30

标签: javascript d3.js force-layout

我已经构建了一个带有分组节点的d3力导向图。我想将这些组封装在云状结构中。我怎么能这样做?

图表的Js Fiddle链接:http://jsfiddle.net/Cfq9J/5/

我的结果应该与此图片类似:

enter image description here

1 个答案:

答案 0 :(得分:11)

这是一个棘手的问题,我不完全确定你能以表演的方式做到这一点。您可以在此处查看我的静态实现:http://jsfiddle.net/nrabinowitz/yPfJH/

以及这里的动态实现,虽然它非常缓慢且抖动:http://jsfiddle.net/nrabinowitz/9a7yy/

有关实施的说明:

  • 这可以通过屏蔽每个圆圈与其组中的所有其他圆圈来实现。您可以通过碰撞检测加快速度。

  • 因为每个圆都被渲染并用作遮罩,所以大量使用use元素来引用每个节点的圆。实际圆圈在def元素中定义,这是一个非重复定义的重新定义。运行此命令时,每个节点将呈现如下:

    <g class="node">
        <defs>
            <circle id="circlelanguages" r="46" transform="translate(388,458)" />
        </defs>
        <mask id="masklanguages">
            <!-- show the circle itself, as a base -->
            <use xlink:href="#circlelanguages" 
                fill="white" 
                stroke-width="2"
                stroke="white"></use>
            <!-- now hide all the other circles in the group -->
            <use class="other" xlink:href="#circleenglish" fill="black"></use>
            <use class="other" xlink:href="#circlereligion" fill="black">
            <!-- ... -->
        </mask>
        <!-- now render the circle, with its custom mask -->
        <use xlink:href="#circlelanguages"
            mask="url(#masklanguages)"
            style="fill: #ffffff; stroke: #1f77b4; " />
    </g>
    
  • 我将节点圈,链接和文本放在不同的g容器中,以便对它们进行适当的分层。

  • 最好在节点数据中包含数据变量,而不是字体大小 - 我必须将fontSize属性转换为整数才能将其用于圆半径。即便如此,因为文本的宽度与数据值无关,所以你会得到一些比它下面的圆圈大的文字。

  • 不确定为什么第一个节点的圆圈没有在静态版本中正确放置 - 它在动态版本中工作。谜。