title: How to calculate the center of a D3 Diagonal Path?
body: <p><strong>Question:</strong> What's the best way to calculate the "<em>center</em>" of a diagonal D3 path?</p>
  
  <p><strong>Visualization Example and Original Source:</strong> <a href="http://bl.ocks.org/Guerino1/raw/ed80661daf8e5fa89b85/" rel="nofollow">http://bl.ocks.org/Guerino1/raw/ed80661daf8e5fa89b85/</a></p>
  
  <p><strong>Goal:</strong> I'm trying overlay link/relationship descriptive text (called "predicates") on paths in a Horizontal D3 Tree.  I'd like to place them in the "<em>center</em>" of the path.  Sometimes the path is a diagonal curve and sometimes it's a straight horizontal line.</p>
  
  <p>For every link path, I have a source node and a target node and I would think that I should be able to calculate the center by using an algorithms like:</p>
  
  <pre><code>For nodes vertically above the root Node...
    xCoordinate = d.target.x - (d.target.x - d.source.x)/2
    yCoordinate = d.source.y - (d.source.y - d.target.y)/2
  
  For nodes vertically below the root Node...
    xCoordinate = d.target.x - (d.target.x - d.source.x)/2
    yCoordinate = d.target.y - (d.target.y - d.source.y)/2
  </code></pre>
  
  <p>Instead, this doesn't work at all.  I read the API reference and it looks like the "<strong>diagonal()</strong>" method might be able to help but it's not clear how to use it.</p>
  
  <p>In the current code block, I get the predicate text to render by appending a  element to the svg canvas and then appending a  to the  element...</p>
  
  <pre><code>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("id", function(d) { return d.source.id + ":" + d.target.id; })
      //.attr("predicate", function(d) { return (linksByIdHash[d.source.id + ":" + d.target.id].predicate); })
      .attr("transform", function(d) { return "translate(" + (d.target.x) + "," + (d.target.y) + ")"; });
  
  // Add Predicate text to each link path
  linkTextEnter.append("svg:foreignObject")
      .attr("width", "150")
      .attr("height", "40")
    .append("xhtml:body")
      .attr("xmlns", "http://www.w3.org/1999/xhtml")
      .html(function(d){ return "&lt;p&gt;" + (linksByIdHash[d.source.id + ":" + d.target.id].predicate) + "&lt;/p&gt;"; });
  </code></pre>
  
  <p>However, the predicate descriptors (i.e. "Predicate 1", "Predicate 2", etc.) are not aligned with the center of each path that they're associated with.</p>
  
  <p>How would I position the predicate text directly on the center of the path?</p>