Welcome to Blogs @ Andrew Qu
Blog Index
All blogs
Search results

How to Check If a Point Is In a Rectanle or not


Shows an algorithm that checks if a point is inside a rectangle or not. The rectangle can be in any orientation.

The Problem

Given 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:

Solution Description
  1. Assume point start is the mid-point of one edge.
  2. Point end is the mid-point of the opposite edge.
  3. Vs is a vector from point start to end.
  4. Now project point P onto vector Vs. The projection point is point Pj.
  5. If Pj is within the line and distance from P to Pj is less than the height, then point P is inside the rectangle.
Javascript code
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 ***
Ads from Google
Dr Li Anchor Profi
Engineering anchorage plate design system
©Andrew Qu, 2015. All rights reserved. Code snippets may be used "AS IS" without any kind of warranty. DIY tips may be followed at your own risk.