Untitled

Jun 23rd, 2022
874
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1.     const DistToLineEx = (p, sA, sB) => {
2.         let dx, dy, d
3.         let f
4.         let result = { nearest: {}, result: 0 }
5.
6.         result.nearest.x = sA.x
7.         result.nearest.y = sA.y
8.         dx = sB.x - sA.x
9.         dy = sB.y - sA.y
10.         d = dx * dx + dy * dy
11.
12.         if (d === 0) {
13.             result.result = Math.hypot(p.x - sA.x, p.y - sA.y)
14.             return result
15.         }
16.
17.         f = ((p.x - sA.x) * dx + (p.y - sA.y) * dy) / d
18.
19.         if (f < 0) {
20.             result.result = Math.hypot(p.x - sA.x, p.y - sA.y)
21.         } else if (f > 1) {
22.             result.nearest = sB
23.             result.result = Math.hypot(p.x - sB.x, p.y - sB.y)
24.         }
25.
26.         result.nearest.x = Math.round(sA.x + f * dx)
27.         result.nearest.y = Math.round(sA.y + f * dy)
28.         result.result = Math.hypot(p.x - result.nearest.x, p.y - result.nearest.y)
29.         return result
30.     }