Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  159] [ 6]  / answers: 1 / hits: 18582  / 8 Years ago, fri, november 18, 2016, 12:00:00

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?


More From » point

 Answers
19

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
}

[#60001] Thursday, November 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jabari

Total Points: 580
Total Questions: 85
Total Answers: 110

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
jabari questions
;