D3.js 强制定向图:当 hexColor 为 null 时更新节点颜色出现问题

问题描述 投票:0回答:1

我正在开发一个 D3.js 强制定向图,其中节点可以有一个 hexColor 字段,该字段有时包含一个字符串形式的十六进制值,有时为 null。我正在尝试根据此 hexColor 字段更新节点的颜色,但当 hexColor 为 null 时遇到问题。

这是我的代码的简化版本:

initChart() {
this.node = this.scene.append("g")
        .attr("stroke", "#fff")
        .attr("stroke-width", 1)
        .selectAll("circle");
}

updateChart({nodes, edges}) {
      const old = new Map(this.node.data().map(d => [d.id, d]));
      nodes = nodes.map(d => ({...old.get(d.id), ...d}));
      edges = edges.map(d => ({...d}));

this.node = this.node
        .data(nodes, d => d.id)
        .join(enter => enter.append("circle")
          .attr("r", 8)
          .attr("fill", d => d.hexColor ?? "#537B87")//TODO node coloring changes doesnt work
          .call(this.drag(this.simulation))
          .call(node => node.append("title")
            .text(d => `IP: ${d.name} ${d.tags ? `\nTags: ${d.tags}` : ''}`))
        );
}

我面临的问题是触发 updateChart 方法时颜色没有更新。

如何修改代码来实现此行为?

任何帮助或建议将不胜感激!预先感谢。

d3.js
1个回答
0
投票

您的

.join
中需要更新回调。 Enter 回调仅在最初添加节点时调用。

this.node = this.node
     .data(nodes, d => d.id)
     .join(
         enter => enter.append("circle")
          .attr("r", 8)          
          .call(this.drag(this.simulation))
          .call(node => node.append("title")
            .text(d => `IP: ${d.name} ${d.tags ? `\nTags: ${d.tags}` : ''}`)),
         update => update.attr("fill", d => d.hexColor ?? "#537B87")
        );
© www.soinside.com 2019 - 2024. All rights reserved.