Javascript: rect.contains(point)

user3432681 picture user3432681 · Nov 19, 2016 · Viewed 12.1k times · Source

I like to see if mouseclick is in a rectangle area (in canvas). In C# i would do this.

var point = new Point(x, y);
var rectangles = new List<Rect>();
//rectangles.add(new Rect(x,y,h,w));
foreach(var rectangle in rectangles)
{
    if(rectangle.Contains(point))
    {
        //do something
    }
}

In Javascript I Tried this

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
if (ctx.isPointInPath(20,50))
   {
     //do something
   };

But there are more rectangles in the context then in my list rectangles. Can somebody help me out?

Answer

thedarklord47 picture thedarklord47 · Nov 19, 2016

if you are going to do anything even slightly complicated with these rects I would define a rectangle object to store, draw, and test for containing points. something like this:

function MyRect (x, y, w, h) {

    this.x = x;
    this.y = y;
    this.width = w;
    this.height = h;

    this.contains = function (x, y) {
        return this.x <= x && x <= this.x + this.width &&
               this.y <= y && y <= this.y + this.height;
    }

    this.draw = function (ctx) {
        ctx.rect(this.x, this.y, this.width, this.height)
    }
}

then use it like this:

var r = new MyRect(x, y, w, h);
r.draw(ctx);

if (r.contains(x, y)) {
    // do something
}