2013-08-02 118 views
6

我正在使用D3绘制有向无环图,我希望能够通过将边(和箭头)的颜色更改为该路径来突出显示选定节点的路径。我很容易改变边缘颜色,但我无法弄清楚如何改变相应的箭头的颜色。我发现most applicable source表明这是不可能的,但它也是大约两年前,所以我期待着看看事情是否发生了变化。我用来创建链接,箭头和更新链接颜色的代码如下:动态箭头颜色

graph.append("svg:defs").selectAll("marker") 
    .data(["end"]) 
    .enter().append("svg:marker")  
    .attr("id", String) 
    .attr("viewBox", "0 -5 10 10") 
    .attr("refX", 20) 
    .attr("refY", 0) 
    .attr("markerWidth", 6) 
    .attr("markerHeight", 6) 
    .attr("orient", "auto") 
    .style("fill", "gray") 
    .append("svg:path") 
    .attr("d", "M0,-5L10,0L0,5"); 

. . . 

var link = graph.append("svg:g").selectAll("line") 
    .data(json.links) 
    .enter().append("svg:line") 
    .style("stroke", "gray") 
    .attr("class", "link") 
    .attr("marker-end", "url(#end)"); 

. . . 

function highlightPath(node) { 
    d3.selectAll("line") 
    .style("stroke", function(d) { 
     if (d.target.name == node) { 
     highlightPath(d.source.name); 
     return "lightcoral"; 
     } else { 
     return "gray"; 
     } 
    }); 
} 

任何建议都会很棒。谢谢。

+0

的可能重复 - ([更改的SVG标记的颜色CSS?] http://stackoverflow.com/questions/16664584/changing-an-svg-markers-color-css) – Josh

+0

谢谢,这没有出现在我的搜索,所以这是一个很好的来源。但是我猜这个时间目前还不能完全使用。 – Valentine

回答

2

不是最好的解决办法,但你可以绘制箭头这样

var arrowHeads = svg.selectAll("polygon.arrowHeads") //arrow heads are triangles 
    .data(links) 
    .enter().append("polygon") 
    .attr("id", function(d, i) {return "arrowHead0" + i}) 
    .attr("points", function(d, i) { 
     //function here that outputs the three points of a triangle 
    }) 
; 

的箭头,其头部具有相同的索引(因为它们具有相同的附加数据)。

所以,你可以使用d3.select("#arrowHead0" + arrowIndex).attr("fill", "black");

8

创建一个函数,给一个返回值,并val应是动态的:

function marker (color) { 
    var val; 
    graph.append("svg:defs").selectAll("marker") 
     .data([val]) 
     .enter().append("svg:marker")  
     .attr("id", String) 
     .attr("viewBox", "0 -5 10 10") 
     .attr("refX", 20) 
     .attr("refY", 0) 
     .attr("markerWidth", 6) 
     .attr("markerHeight", 6) 
     .attr("orient", "auto") 
     .style("fill", color) 
     .append("svg:path") 
     .attr("d", "M0,-5L10,0L0,5"); 
    return "url(#" +val+ ")"; 
} 

var link = graph.append("svg:g").selectAll("line") 
       .data(json.links) 
       .enter().append("svg:line") 
       .style("stroke", "gray") 
       .attr("class", "link") 
       .attr("marker-end", marker); //"url(#end)"