PROBLEM: Link text is not rendering.
GOAL: To add link text to each path in a manner that 1) allows text wrapping and 2) ensures that text will transition in and out as nodes are selected/deselected.
ORIGINAL SOURCE: Located at: http://bl.ocks.org/Guerino1/raw/ed80661daf8e5fa89b85/
Every relationship/link has a descriptive predicate that can be seen in the data...
var linkSet = [
{source: "N0", predicate: "Predicate 1", target: "N1"},
{source: "N1", predicate: "Predicate 2", target: "N2"},
{source: "N2", predicate: "Predicate 3", target: "N3"},
{source: "N0", predicate: "Predicate 4", target: "N4"},
{source: "N4", predicate: "Predicate 5", target: "N5"},
{source: "N0", predicate: "Predicate 6", target: "N6"},
{source: "N6", predicate: "Predicate 7", target: "N7"},
{source: "N6", predicate: "Predicate 8", target: "N8"},
{source: "N7", predicate: "Predicate 9", target: "N9"},
{source: "N7", predicate: "Predicate 10", target: "N10"}
];
I try an apply that predicate to each path, via a foreignObject with the intent that I'll be able to wrap predicate text, just like node text is wrapped. The foreignObject is appended to the "path" element. The code I use look as follows...
// Add Predicate text to each link path
link.append("svg:foreignObject")
.data(linkSet)
.attr("width", "200")
.attr("height", "40")
.append("xhtml:body")
.attr("xmlns", "http://www.w3.org/1999/xhtml")
.html(function(d){ return "<p>" + d.predicate + "</p>"; });
However, while the DOM Tree shows that the foreignObject and the html "p" element are added and exist the text does not render.
The answer is to add <g>
elements to the SVG at the centroid of each path and then append <foreignObject>
elements to each <g>
element...
var linkTextItems = vis.selectAll("g.linkText")
.data(tree.links(nodes), function(d) { return d.target.id; })
var linkTextEnter = linkTextItems.enter().append("svg:g")
.attr("class", "linkText")
.attr("transform", function(d) { return "translate(" + (d.target.y + 20) + "," + (getCenterX(d)) + ")"; });
// Add Predicate text to each link path
linkTextEnter.append("svg:foreignObject")
.attr("width", "120")
.attr("height", "40")
.append("xhtml:body")
.attr("xmlns", "http://www.w3.org/1999/xhtml")
.html(function(d){ return "<p>" + (linksByIdHash[d.source.id + ":" + d.target.id].predicate) + "</p>"; });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.