Reputation: 10567
I'm trying to add labels to a force graph that is created dynamically. Here is the code.
This is the relevant part of the code where I add the text elements.
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");
Here is a fiddle I created that demonstrates the problem. - https://jsfiddle.net/soorajchn/u49s9sth/
(Since its large stackoverflow
does not allow me to create the code snippet of that size )
If i click the add button a node will be created and a connecting line can be drawn by dragging from one node to another. To move around a node use ctrl + drag.
I'm trying to add the label and the text element is getting added. But it always takes up 0 height and width and ends up at top left corner of the screen. What am i doing wrong ?
Upvotes: 2
Views: 75
Reputation: 14591
You missed to set the ID to the path elements. Try this way.
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();
});
Updated fiddle
Upvotes: 3