Skip to content

Instantly share code, notes, and snippets.

@dwtkns
Created November 10, 2015 03:14
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 dwtkns/d5b9b60285b8b0067c53 to your computer and use it in GitHub Desktop.
Save dwtkns/d5b9b60285b8b0067c53 to your computer and use it in GitHub Desktop.
Finds the location on the perimeter of a given rectangle that is closest to a given point.
// translated from http://stackoverflow.com/questions/20453545/how-to-find-the-nearest-point-in-the-perimeter-of-a-rectangle-to-a-given-point
function clamp(n,lower,upper) {
return Math.max(lower, Math.min(upper, n));
}
function getNearestPointInPerimeter(l,t,w,h,x,y) {
var r = l+w,
b = t+h;
var x = clamp(x,l,r),
y = clamp(y,t,b);
var dl = Math.abs(x-l),
dr = Math.abs(x-r),
dt = Math.abs(y-t),
db = Math.abs(y-b);
var m = Math.min(dl,dr,dt,db);
return (m===dt) ? [x,t] :
(m===db) ? [x,b] :
(m===dl) ? [l,y] : [r,y];
}
Copy link

ghost commented May 27, 2020

This works great in certain programming languages, but how would I clamp the nearest point on the rectangle when I don't have access to a function that does that? I know how, but it takes more code than I would like and I want to find a simple way to do it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment