Neil Benn
unread,Jul 26, 2011, 12:53:53 PM7/26/11Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to d3-js
Hi all,
I'm new to D3 and already enjoying experimenting with it and getting
more familiar with it.
I have been using the 'force.js' example distributed with the code as
a starting point and just adding little modifications here and there.
One modification I am trying is placing text labels on the lines in
the graph. I'm also new to SVG but I noticed I can use 'textPath' to
put text on lines. So here are snippets of the code that I modified
from the original 'force.js' example:
First, the original:
------
var link = vis.selectAll("line.link")
.data(json.links)
.enter().append("svg:line")
.attr("class", "link")
.style("stroke-width", function(d) { return
Math.sqrt(d.value); })
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
------
Now the modified version (in the JSON data I added a "label"
attribute):
------
var link = vis.selectAll("path.link")
.data(json.links)
.enter().append("svg:path")
.attr("class", "link")
.attr("id",
function(d) {
return "path"+d.source.index+"_"+d.target.index;
})
.attr("d",
function(d) {
return moveto(d) + lineto(d);
});
function moveto (d) {
return "M"+d.source.x+","+d.source.y;
};
function lineto (d) {
return " L"+d.target.x+","+d.target.y;
};
var label = vis.selectAll("text")
.data(json.links)
.enter().append("svg:text")
.attr("font-size", 10)
.append("svg:textPath")
.attr("xlink:href",
function(d) {
return "#path"+d.source.index+"_"+d.target.index;
})
.text(function(d){ return d.label; });
force.on("tick", function() {
link.attr("d",
function(d) {
return moveto(d) + lineto(d);
});
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
------
This works fine in Firefox -- the label is displayed on the line and
even as the nodes move around during the "ticking" of the graph, the
labels remain firmly placed on the line. Not so in Safari.
For some reason in Safari, when the graph loads, the labels appear but
then as the nodes move around, the labels are left behind and the
lines appear without any labels.
Does anyone have any idea about why the behaviour is different in
Safari? And any ideas about a possible fix?
Many thanks for any help or suggestions,
Neil