2

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 Answers1

1

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 + ')';
    }
  });
enxaneta
  • 31,608
  • 5
  • 29
  • 42
  • thanks a lot for the solution! Have updated the fiddle: http://jsfiddle.net/vygjt21h/ to show the solution in action. Just in case anyone is curious as to why it works with atan2 and not completely with atan, look here: https://stackoverflow.com/questions/283406/what-is-the-difference-between-atan-and-atan2-in-c/12011762#12011762 (the explanation for is also applicable atan2/atan in javascript) – Astro Zigzag Oct 13 '19 at 17:08