D3 force layout: rotating text

Viewed 130

I am using an example which was used to rotate a label in a d3's force layout. I am trying to display the label text '<' such that A is displayed always < B. Please refer the fiddle: http://jsfiddle.net/xr3917ac/4/

However, as the node A is dragged in circular motion, the label text '<' suddenly flips 180 degrees displaying B < A. How can this flip be avoided so that the A is displayed < B always? The rotation angle of the label is calculated in tick():

const dsty = d.source.y - d.target.y;
let angle = Math.atan(dsty / (d.source.x - d.target.x)) * 180 / Math.PI;
      return 'translate(' + [((d.source.x + d.target.x) / 2), ((d.source.y + d.target.y) / 2)] + ')rotate(' + angle + ')';
1 Answers

Use Math.atan2instead of Math.atan

labelLine.attr("transform", function(d) {
    if (d) {
      const dsty = d.source.y - d.target.y;
      let angle = Math.atan2(dsty, (d.source.x - d.target.x)) * 180 / Math.PI;
      return 'translate(' + [((d.source.x + d.target.x) / 2), ((d.source.y + d.target.y) / 2)] + ')rotate(' + angle + ')';
    }
  });
Related