Created
November 10, 2015 03:14
-
-
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.
This file contains hidden or 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
// 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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.