D3.js力导向图:hexColor为null时节点颜色无法更新的问题
D3.js力导向图节点颜色更新问题解决方案
你的问题出在join方法只处理了新创建的节点(enter选择集),但没有对已存在的节点(update选择集)更新颜色属性。当触发updateChart时,已有节点的数据虽然更新了,但对应的DOM元素样式没有同步修改。
修改后的代码
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") .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") ); }
关键说明
join方法可以接受三个参数,分别对应enter、update、exit三个选择集的处理逻辑- 新增的
update分支会遍历所有已存在的节点,根据最新的hexColor值更新填充色,包括hexColor为null时使用默认值#537B87 - 如果需要同步更新其他属性(比如半径、title文本),也可以在
update分支中添加对应的attr或text方法
内容的提问来源于stack exchange,提问作者SHIFD
相关产品推荐
相关产品推荐

