How to Check If a Point Is In a Rectanle or not
SummaryShows an algorithm that checks if a point is inside a rectangle or not. The rectangle can be in any orientation.
The ProblemGiven a rectangle orientated in any way on the XY plane. Check if a given point P is inside the rectangle or not. This is dipicted in the picture below:

- Assume point start is the mid-point of one edge.
- Point end is the mid-point of the opposite edge.
- Vs is a vector from point start to end.
- Now project point P onto vector Vs. The projection point is point Pj.
- If Pj is within the line and distance from P to Pj is less than the height, then point P is inside the rectangle.
function PointVector(xx, yy) {
this.x = xx;
this.y = yy;
this.length = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
this.lengthSquared = function() {
return this.x * this.x + this.y * this.y;
}
}
function IsPointInRectangle(p, start, end, h) {
// Vector from start to end
var Vs = new PointVector(end.x - start.x, end.y - start.y);
// Vector from start to P
var Vp = new PointVector(p.x - start.x, p.y - start.y);
// Project Vp onto Vs, get length from start to Pj
var Lj = (Vs.x * Vp.x + Vs.y * Vp.y) / Vs.length();
// If Pj is outside of the line, then P is outside
if (Lj < 0 || Lj > Vs.length()) return false;
// Distance from P to Pj
var Hj = Math.sqrt(Vp.lengthSquared() - Lj * Lj);
return Hj > h ? false : true;
}
// Test code
var res = IsPointInRectangle(new PointVector(100.0, 100.0),
new PointVector(0.0, 0.0), new PointVector(200.0, 0.0), 110.0);
*** END ***