# Nearest Point To Square //JavaScript Repository

## Description

Nearest point to a square, given a point out of the limits.
Created: 2005.08.20

``````//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/closest-square-point [rev. #1]

closestSquarePoint = function(px, py, x, y, w, h){
return {x: px < x ? x : px > x + w ? x + w : px, y: py < y ? y : py > y + h ? y + h : py};
};``````

## Example (Example)

``````<div id="retangulo" style="position: absolute; background: #eef; width: 200px; height: 200px; left:200px; top: 200px;">Mova o mouse fora da ?rea do ret?ngulo</div>
<div id="dot" style="position: absolute; border:1px solid #000; background: #fee; width: 20px; height: 20px;"></div>

<script type="text/javascript">
//<![CDATA[

var square = document.getElementById("retangulo"), box = document.getElementById("dot");

//http://www.jsfromhell.com/geral/event-listener
var p = closestSquarePoint(e.clientX, e.clientY, square.offsetLeft, square.offsetTop, square.offsetWidth, square.offsetHeight);
box.style.left = (p.x - box.offsetWidth / 2) + "px";
box.style.top = (p.y - box.offsetHeight / 2) + "px";
});

//]]>
</script>``````

## Help

closestSquarePoint(px: Integer, py: Integer, x: Integer, y: Integer, width: Integer, height: Integer): Object
Returns a object containing two properties (x and y), that specifies the limit point of a square in relation to a point.
px
x coord of the point
py
y coord of the point
x
x coord of the square origin point
y
y coord of the square origin point
width
width of the square
height
height of the square

4.11