0

I have all coordinates but Px, and I need to find the distance between Px and the Mouse Location(red line). It will be implemented on javascript, any ideas?

fabriciofreitag
  • 2,843
  • 22
  • 26
  • http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html with the assumption you mean perpendicular distance – pvg Dec 12 '15 at 21:32
  • yes, also assuming that the mouse can be anywhere else, on both sides of the blue line – fabriciofreitag Dec 12 '15 at 21:36
  • answer is listed right in the linked page. scroll down to 'line defined by two points' – pvg Dec 12 '15 at 21:40

1 Answers1

1

There you go:

var P1 = {x: 10, y: 5},
    P2 = {x: 8,  y: 4},
    PM = {x: 2,  y: 5};

function distance(source, target1, target2) {
    var zaehler = Math.abs((target2.x - target1.x)*(target1.y - source.y) - (target1.x - source.x)*(target2.y - target1.y));
    var nenner = Math.sqrt(Math.pow(target2.x - target1.x, 2) + Math.pow(target2.y - target1.y, 2));
    return zaehler/nenner;
}

console.log(distance(PM, P2, P1) === distance(PM, P1, P2));
Chris
  • 4,204
  • 1
  • 25
  • 30