Last active
May 19, 2020 03:44
-
-
Save ikekou/cf110922a133879279ffedf24d1f6c5f to your computer and use it in GitHub Desktop.
get closest point on line with specific point
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function closestXY(x0,y0,x1,y1, mx, my) { | |
var dx = x1 - x0; | |
var dy = y1 - y0; | |
var t = ((mx - x0) * dx + (my - y0) * dy) / (dx * dx + dy * dy); | |
t = Math.max(0, Math.min(1, t)); | |
var x = lerp(x0, x1, t); | |
var y = lerp(y0, y1, t); | |
return ({x: x, y: y}); | |
} | |
function lerp(value1, value2, amount) { | |
amount = amount < 0 ? 0 : amount; | |
amount = amount > 1 ? 1 : amount; | |
return value1 + (value2 - value1) * amount; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment