Skip to content

Instantly share code, notes, and snippets.

@ikekou
Last active May 19, 2020 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikekou/cf110922a133879279ffedf24d1f6c5f to your computer and use it in GitHub Desktop.
Save ikekou/cf110922a133879279ffedf24d1f6c5f to your computer and use it in GitHub Desktop.
get closest point on line with specific point
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