力导向图d3.js自定义箭头颜色

时间:2016-11-22 11:55:02

标签: javascript d3.js

我按照http://bl.ocks.org/mbostock/4062045中的教程和问题Introducing Arrow(directed), in Force Directed Graph d3进行操作,并可以通过

自定义边缘颜色
  var svg_edges = svg.append("svg:g").selectAll("path")
                        .data(force.links())
                        .enter()
                        .append("line")
                        .style("stroke",function(d,i){
                         return color(i); // customize edges colors
                        })

然后按以下代码添加箭头:

        svg.append("svg:defs").selectAll("marker")
        .data(['end'])      // Different link/path types can be defined here
      .enter().append("svg:marker")    // This section adds in the arrows
        .attr("id", function(d,i) { 
            return d; 
        })
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 15)
        .attr("refY", 0)
        .attr("markerWidth", 6)
        .attr("markerHeight", 6)
        .attr("orient", "auto")
      .append("svg:path")
        .attr("d", "M0,-5L10,0L0,5")
        .style("fill", "#ccc")  // how to customize each arrow color here

然后在边缘添加

.attr("marker-end", "url(#end)");

我想知道如何指定每个箭头的颜色,就像我们在边缘上做的那样。 http://bl.ocks.org/mbostock/1153292显示如何指定不同类型的边和箭头,但我没有找到通过编码更改(箭头和边)的方法。

1 个答案:

答案 0 :(得分:1)

在我的测试中添加边类,在{0,1}

中添加d [" value]
 svg_edges.attr("marker-end", function(d) { return "url(#arrow" + d["value"] + ")"; });
箭头定义中的

svg.append("svg:defs").selectAll("marker")
   .data(['0','1'])      //same as  d["value] in {0, 1}
   .enter().append("svg:marker")    // This section adds in the arrows
   .attr("id", function(d,i) { return "arrow" + d; }) 

in css style

#arrow0 {
    fill: #ccc;
} 
#arrow1 {
    fill: red;
}

然后,你明白了。

相关问题