添加链接文本到动画D3树

Adding Link Text to Animated D3 Tree

本文关键字:D3 动画 链接 文本 添加      更新时间:2023-09-26

问题:链接文本未显示

目标:添加链接文本到每个路径的方式,1)允许文本换行,2)确保文本将在节点被选中/取消选中时转换。

原始来源:位于:http://bl.ocks.org/Guerino1/raw/ed80661daf8e5fa89b85/

每个关系/链接都有一个描述性谓词,可以在数据中看到…

  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"}
  ];

我尝试应用谓词到每个路径,通过一个foreignObject的意图,我将能够包装谓词文本,就像节点文本被包装。foreignObject被附加到"path"元素。我使用的代码如下所示…

// 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>"; });

但是,虽然DOM树显示添加了foreignObject和html "p"元素并且存在,但文本没有呈现

答案是在每个路径的质心处将<g>元素添加到SVG,然后将<foreignObject>元素附加到每个<g>元素…

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>"; });