【发布时间】:2020-05-02 13:57:27
【问题描述】:
我是 d3 的新手,还在学习。 我有 node 和 link 作为 d3 中的变量,它们从给定的 json 数据格式中选择相应的节点和链接/图形。 我编写了一个函数来根据每个链接的 source 和 target 名称更改其颜色。 p>
我无法理解的是,在变量 node 上调用此函数也会改变链接的颜色。那么我在什么对象上调用这个函数是否重要呢? d 变量是否会根据我调用函数的内容在内部从节点更改为链接?
代码
//How link is defined
var link=svg
.append("g")
.selectAll("line")
.data(graph.links)
.enter()
.append("line")
.attr("stroke-width",function(d){
return 3
})
.style("stroke","pink")
.text("text",function(d){return d.name});
//How node is defined
var node =svg
.append("g")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("circle")
.attr("r",5)
.attr("fill", function(d){
return "orange"
})
.attr("stroke","yellow")
;
//link.call(updateState1)
//This works as it should
node.call(updateState1)
// I can't understand why this line works too.
function updateState1() {
link
.each(function(d) {
var colors=["red","green","blue"]
var num=0;
if(d.source.name.length>d.target.name.length)
{
num=1;
console.log("Inside 1");
console.log("Source is ",d.source.name," and target is ",d.target.name);
}
else if(d.source.name.length<d.target.name.length)
{
num=2;
console.log("Inside 2");
console.log("Source is ",d.source.name," and target is ",d.target.name);
}
else{
num=0;
}
// your update code here as it was in your example
d3
.select(this)
.style("stroke", function(d){ return colors[num]})
.attr('marker-end','url(#arrowhead)');
});
}
【问题讨论】:
标签: javascript d3.js