Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: rect.contains(point)

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?

like image 879
user3432681 Avatar asked Nov 18 '16 23:11

user3432681


3 Answers

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
}
like image 105
thedarklord47 Avatar answered Oct 06 '22 09:10

thedarklord47


You could calculate it yourself

Save the bonds of the rects, draw them, and then look if the mouse is over them

let rects = [{x: 20, y: 20, w: 150, h: 100}]
let mouse = ...
for (let rect of rects) {
  ctx.fillRect(rect.x, rect.y, rect.w, rect.h)
  if(mouse.x >= rect.x && mouse.x <= rect.x + rect.w && mouse.y >= rect.y && mouse.y <= rect.y + rect.h){
    //do something
  }
}
like image 44
Julian Avatar answered Oct 06 '22 07:10

Julian


You should've stored your rectangle points, if you wish to work on it after you've used it for drawing. Since in canvas, you're only able to draw on it and not retrieving any drawn points from it.

Old good way would be like,

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var rectangles = [
  [20, 20, 50, 50],
  [70, 70, 80, 80],
  [150, 150, 110, 110]
];

for (var i = 0; i < rectangles.length; i++) {
  ctx.fillRect(...rectangles[i]);
}

var isPointInRects = function(x, y) {
  for (var i = 0; i < rectangles.length; i++) {
    var xStart = rectangles[i][0],
      yStart = rectangles[i][1],
      xEnd = xStart + rectangles[i][2],
      yEnd = yStart + rectangles[i][3];

    if ((x >= xStart && x <= xEnd) &&
      (y >= yStart && y <= yEnd)) {
      return true;
    }
  }
  return false;
};

console.log(isPointInRects(20, 20));
<canvas id="myCanvas" width=500 height=500></canvas>
like image 35
choz Avatar answered Oct 06 '22 09:10

choz