在力图d3上添加标签

时间:2016-09-06 05:16:59

标签: javascript jquery d3.js

我试图将标签添加到动态创建的力图中。这是代码。

这是我添加文本元素的代码的相关部分。

labels = labels.data(links);

labels.exit().remove();

labels.enter()
    .append("text")
    .attr("text-anchor", "middle")
    .attr("x", 0)
    .attr("dy", 16)
    .append("textPath")
    .attr("startOffset", "50%")
    .attr("xlink:href", function(d,i){ return "#id" + i})
    .text("label");

这是我创建的一个小提琴,用于演示问题。 - https://jsfiddle.net/soorajchn/u49s9sth/

(因为它的大stackoverflow不允许我创建那个大小的代码片段)

如果单击“添加”按钮,将创建一个节点,并且可以通过从一个节点拖动到另一个节点来绘制连接线。要在节点中移动,请使用ctrl + drag。

我正在尝试添加标签,并且正在添加文本元素。但它总是占用0高度和宽度,最终在屏幕的左上角。我究竟做错了什么 ?

1 个答案:

答案 0 :(得分:3)

您错过了将ID设置为路径元素。试试这种方式。

 path.enter().append('svg:path')
    .attr('class', 'link')
    .attr("id",function(d, i) {
      return "id" + i; //Sets id to the path elements which will be used in textPaths later
    })
    .classed('selected', function(d) {
      return d === selected_link;
    })
    .style('marker-start', function(d) {
      return d.left ? 'url(#start-arrow)' : '';
    })
    .style('marker-end', function(d) {
      return d.right ? 'url(#end-arrow)' : '';
    })
    .on('mousedown', function(d) {
      if (d3.event.ctrlKey) return;

      // select link
      mousedown_link = d;
      if (mousedown_link === selected_link) selected_link = null;
      else selected_link = mousedown_link;
      selected_node = null;
      restart();
    });

更新了fiddle

相关问题