Javascript: rect.contains(point)

8

我想知道鼠标点击是否在矩形区域内(在画布中)。 在C#中,我会这样做。

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
    }
}

我在JavaScript中尝试过这个:

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

但是在上下文中有比我的矩形列表更多的矩形。有人能帮我解决吗?


定义一个对象,它存储矩形的参数,同时绘制自身并测试包含的点。 - thedarklord47
3个回答

15

如果你要对这些矩形进行稍微复杂一点的操作,我建议定义一个矩形对象来存储、绘制和检测是否包含某个点。类似这样:

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)
    }
}

然后像这样使用它:

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

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

5
你可以自己计算一下!
保存矩形的边界,绘制它们,然后查看鼠标是否在其上方。
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
  }
}

2
如果您希望在绘制后继续操作矩形,请存储您的矩形点。因为在画布中,您只能在其上绘制,而无法从中检索任何绘制的点。
传统方法可能是:

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接