简体   繁体   English

使用D3进行有色力的布局

[英]Using D3 to make a colored force layout

How can I make a colored force directed layout using D3.v4 and canvas ? 如何使用D3.v4canvas进行有色力导向的布局?

I am not sure how to color the nodes. 我不确定如何给节点着色。

We can use this example as a reference. 我们可以将此示例作为参考。

Adding color into this function: 在此函数中添加颜色:

var color = d3.scaleOrdinal(d3.schemeCategory10);

function drawNode(d) {
  context.moveTo(d.x + 3, d.y);
  context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
  context.fillStyle = function(d) {
    // d.group is either a 1 or a 2
    return color(d.group)
  }
  context.fill()
}

The above code makes the graphic really laggy so I am thinking that that is not the best way to do it. 上面的代码使图形变得非常缓慢,因此我认为这不是最好的方法。 Additionally, the above code colors all nodes in same color even if they are in separate groups. 此外,以上代码为所有节点都以相同的颜色着色,即使它们在单独的组中也是如此。

You can find the full code here 您可以在此处找到完整的代码

Edit: for clarity, I'd like to use canvas for performance reasons. 编辑:为了清楚起见,出于性能原因,我想使用canvas。 I've managed to get it to work with SVGs but that makes panning and zooming very slow. 我已经设法使其与SVG一起使用,但这使平移和缩放非常慢。

I cannot help for the performance without seeing the whole application. 在看不到整个应用程序的情况下,我无法提供帮助。 But for the color issue, the solution is: 但是对于颜色问题,解决方案是:

  context.fillStyle = color(d.group)

The solution was to add context.beginPath() to the function. 解决方案是将context.beginPath()添加到函数中。

The final function now looks like this: 现在,最终功能如下所示:

function drawNode(d) {
    context.fillStyle = color(d.group);
    context.beginPath();
    context.moveTo(d.x + 3, d.y);
    if(d.group == 1){
        context.arc(d.x, d.y, 17 * Math.log(1.25 * Math.pow(d.winCount, 0.25)) + 3, 0, 2 * Math.PI);
    }else{
        context.arc(d.x, d.y, 3.75 * Math.log(Math.pow(d.winCount, 0.75)) + 4, 0, 2 * Math.PI);
    }
    context.fill();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM