How can I append text to and render that text from

2019-02-20 13:52发布

问题:

I'm trying to learn how to use the force.layout features in D3.js and have been building a "Force Directed Radial Graph".

I've been able to successfully append and render text from nodes (e.g. Node Names) but I can't seem to get text to render from the lines (or what others might call the links or edges) (e.g. Relationship Names).

Does anyone know where I can find good examples that teach how to do so or have code snippets that can correct what I've done?

Thanks for any help you can offer. It's greatly appreciated.

My Best,

Frank

回答1:

The sample already shows how to add text to the edges. Here is the relevant piece of code:

      // Append text to Link edges
  var linkText = svgCanvas.selectAll(".gLink")
      .data(force.links())
    .append("text")
  .attr("font-family", "Arial, Helvetica, sans-serif")
  .attr("x", function(d) {
      if (d.target.x > d.source.x) { return (d.source.x + (d.target.x - d.source.x)/2); }
      else { return (d.target.x + (d.source.x - d.target.x)/2); }
  })
      .attr("y", function(d) {
      if (d.target.y > d.source.y) { return (d.source.y + (d.target.y - d.source.y)/2); }
      else { return (d.target.y + (d.source.y - d.target.y)/2); }
  })
  .attr("fill", "Maroon")
      .style("font", "normal 12px Arial")
      .attr("dy", ".35em")
      .text(function(d) { return d.linkName; });