Analyzing a point along a line
How to compute the relative position of point w, between points a and b.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
*
* @param {[x,y]} a line end-point
* @param {[x,y]} b line end-point
* @param {[x,y]} w point to test
* @returns {object or null} Returns null if ((a == b) and (c != a)), otherwise
* return an object like:
* {
* t {real} : fractional distance between a and b,
* i {[x, y] : perpendicular point of intersection between a and b,
* d {real} : distance from i to the test point (w)
* d > 0 ==> d is to the right of a-b,
* d < 0 ==> d is to the left of a-b
* }
*/
function PointAlongLine(a, b, w) {
var ax = a[0], ay = a[1];
var bx = b[0], by = b[1];
var wx = w[0], wy = w[1];
if (ax === bx && ay === by) {
if (ax === wx && ay === wy) {
return {t: 1, i: [ax, ay], d: 0};
} else {
return null;
}
}
var denom = Math.pow(bx - ax, 2) + Math.pow(by - ay, 2);
var t = ((wx - ax) * (bx - ax) + (wy - ay) * (by - ay)) / (denom);
var ix = ax + t * (bx - ax);
var iy = ay + t * (by - ay);
var dist = ((by - ay) * wx - (bx - ax) * wy + bx * ay - by * ax) / (Math.sqrt(denom));
return {
t: t,
i: [ix, iy],
d: dist
};
}