Point in Rectangle

Fri May 02 2025 15:06:07 GMT+0100 (British Summer Time) geometryfunctionjavascriptarchived

Rectangle bounds test

This simple method allows testing of a coordinate in 2D space against the X,Y position and Width and Height of a given rectangle to determine if the point falls within the rectangles bounds.

View example

function pointInRect(x, y, rx, ry, rw, rh)
{
    return (x>=rx && x<=(rx+rw) && y>=ry && y<=(ry+rh));
}

Example source code


<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">
var ctx = null, game = null;
var mouseX = -1, mouseY = -1;
var isOver = false;
var rect = { x:250, y:150, w:100, h:100 };

window.onload = function() {
    game = document.getElementById('game');
    ctx = game.getContext('2d');

    game.addEventListener('mousemove', function(e) {
        mouseX = e.pageX;
        mouseY = e.pageY;

        // Calculate actual mouse position on Canvas
        var p = game;
        do
        {
            mouseX-= p.offsetLeft;
            mouseY-= p.offsetTop;

            p = p.offsetParent;
        } while(p!=null);

        // See if cursor is over the rectangle...
        isOver = pointInRect(mouseX, mouseY,
            rect.x, rect.y, rect.w, rect.h);
    });

    requestAnimationFrame(drawGame);
};

function pointInRect(x, y, rx, ry, rw, rh)
{
    return (x>=rx && x<=(rx+rw) && y>=ry && y<=(ry+rh));
}

function drawGame()
{
    if(ctx==null) { return; }

    // Set fill and stroke colours dependant on whether or not the
    // cursor is over the rectangle
    if(isOver)
    {
        ctx.fillStyle = "#ff9999";
        ctx.strokeStyle = "#ff3333";
    }
    else
    {
        ctx.fillStyle = "#aaaacc";
        ctx.strokeStyle = "#7777aa";
    }

    // Draw the rectangle
    ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
    ctx.strokeRect(rect.x, rect.y, rect.w, rect.h);

    // Request the next animation frame
    requestAnimationFrame(drawGame);
}
</script>
</head>
<body>

<p>Move your mouse cursor on and off the rectangle below.</p>
<p>If you do not see a rectangle, check your browser supports Canvas elements, and has Javascript enabled.</p>

<canvas id="game" width="600" height="400"></canvas>

</body>
</html>