Javascript函数确定一个点是否在矩形之间 [英] Javascript function to determine if a point is in between a rectangle

查看:193
本文介绍了Javascript函数确定一个点是否在矩形之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Javascript函数,它没有返回我预期的结果。我试图确定基于2个其他x,y点的矩形内是否存在x,y点。在我的代码中,x和y是有问题的原始点。 z1和z2是矩形的左上角坐标,z3和z4是右下角的坐标。

I have a Javascript function that isn't returning the result I expected. I am trying to determine if an x,y point exists within a rectangle based on 2 other x,y points. In my code x and y are the original point in question. z1 and z2 are the top left coordinates of the rectangle and z3 and z4 are the bottom right coordinates.

function isInside(x,y,z1,z2,z3,z4){
x1 = Math.min(z1, z3);
x2 = Math.max(z1, z3);
y1 = Math.min(z2, z4);
y2 = Math.max(z2, z4);
if ((x1 <= x <= x2) && (y1 <= y <= y2)) {
 console.log (x1 + "," + x + "," + x2); 
 console.log (y1 + "," + y + "," + y2);
 return true;
} else {
 return false;
};
};

如果我评价isInside(110,175,50,50,100,100)我会变成现实。这是出乎意料的,因为点150,175不存在于50,50和100,100的矩形内。任何帮助将不胜感激。

If I evaluate isInside(110,175,50,50,100,100) I am getting true. This is unexpected as point 110,175 does not exist within a rectangle of 50,50 and 100,100. Any help would be appreciated.

推荐答案

(x1< = x< = x2)无法在Javascript中执行您想要的操作:您必须使用 x1< = x&& x< = x2

(x1 <= x <= x2) doesn't do what you want it to do in Javascript: you have to use x1 <= x && x <= x2.

如果您插入这些变量的实际数字并在Chrome的控制台中尝试这一点,您可以看到整个语句总是评估为真:

If you plug in actual numbers in for those variables and try this out in Chrome's console, you can see that the whole statement always evaluates to true:

1 <= 3 <= 5
true
9 <= 3 <= 5
true

这篇关于Javascript函数确定一个点是否在矩形之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆