我有一个 D3.js 树,它对节点和链接应用了不同的颜色。
着色是硬编码的:
nodeUpdate.select("circle")
.attr("r", 10)
.style("fill", function(d) {
if(d.name == "Top Level") {
return d._children ? "blue" : "#fff";
}
if(d.name == "Second A") {
return d._children ? "red" : "#fff";
}
if(d.name == "Second B") {
return d._children ? "green" : "#fff";
}
if(d.name == "Second C") {
return d._children ? "purple" : "#fff";
}
if(d.name == "Second D") {
return d._children ? "gold" : "#fff";
}
})
.style("stroke", function(d) {
if(d.name == "Top Level") {
return "blue";
}
if(d.name == "Second A") {
return "red";
}
if(d.name == "Second B") {
return "green";
}
if(d.name == "Second C") {
return "purple";
}
if(d.name == "Second D") {
return "gold";
}
});
和
link.enter().insert("path", "g")
.attr("class", "link")
.attr("stroke-width", function(d){
return 1;
})
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.style("stroke", function(d) {
return linkColor(d.target.name);
});
和
function linkColor(node_name) {
switch (node_name)
{
case 'Second A': case 'Third A': case 'Third B':
return 'red';
break;
case 'Second B': case 'Third C': case 'Third D':
return 'green';
break;
case 'Second C': case 'Third E': case 'Third F':
return 'purple';
break;
case 'Second D': case 'Third G': case 'Third H':
return 'gold';
}
}
相关分类