thednp
thednp

Reputation: 4479

Javascript: How to determine a SVG path draw direction?

I'm trying to determine a SVG path draw orientation. I'm working on something like this

var length = path.getTotalLength();
var horizontal = path.getPointAtLength(length/4).x - path.getPointAtLength(0).x;
var vertical = path.getPointAtLength(length/4).y - path.getPointAtLength(0).y;

Then do some comparisons with these values horizontal > 0 and vertical > 0, but this above idea isn't, in my mind, very successful.

My question is: is there anything I can use to determine the draw direction or perhaps some built in SVG methods/options?

Thank you

Upvotes: 7

Views: 2676

Answers (1)

Andrew Willems
Andrew Willems

Reputation: 12458

Use Math.atan2(yDiff, xDiff) to get the angle between the two reference points. Two visually identical shapes that go in opposite directions will have an angle difference of pi.

Be aware of the edge case where your two reference points are unluckily the same point. Not likely, especially given rounding errors, but keep it in mind in case you need this to be rock solid.

var paths = document.getElementsByTagName("path");
for (var pathNum = 0; pathNum < paths.length; pathNum += 1) {
  var path = paths[pathNum];
  var message = document.createElement('p');
  message.innerHTML = "path #" + pathNum + ": angle = " + pathDir(path);
  document.body.appendChild(message);
};

function pathDir(path) {
  var length = path.getTotalLength();
  var pt14 = path.getPointAtLength(1/4 * length);
  var pt34 = path.getPointAtLength(3/4 * length);
  var angle = Math.atan2(pt14.y - pt34.y, pt14.x - pt34.x);
  return angle;
}
<svg width="300" height="80">
  <g fill="none" stroke="black" stroke-width="4">
    <path d="M 10,10 C 90,10 -30,60  50,60Z"/>
    <path d="M110,10 C190,10  70,60 150,60Z"/>
    <path d="M250,60 C170,60 290,10 210,10Z"/>
  </g>
</svg>
<div></div>

Upvotes: 6

Related Questions