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?
Asked
Active
Viewed 49 times
0
-
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 Answers
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
-
I'm confused with distance's parameters, but I think I know what you meant – fabriciofreitag Dec 12 '15 at 22:05
-
thank you so much, extra small question, can I tell whenever the mouse crosses the blue line? – fabriciofreitag Dec 12 '15 at 22:29
-
answering my previous question: http://stackoverflow.com/questions/1560492/how-to-tell-whether-a-point-is-to-the-right-or-left-side-of-a-line – fabriciofreitag Dec 12 '15 at 22:37