判断相交

来源:互联网 发布:网络大电影运营模式 编辑:程序博客网 时间:2024/05/14 14:07
**
* 判断线段ab与线段cd是否相交,两线段重叠或交点为顶点视为不相交
*/
var isIntersection = function(a, b, c, d) {
var flag = false;
if (a == c && b == d
|| b == c
|| b == d
|| a == d
|| (b.y - a.y) * (c.x - d.x) - (c.y - d.y) * (b.x - a.x) == 0) {
return flag;
}
var intersection = new OpenLayers.Geometry.Point();
intersection.x = ((b.x - a.x) * (c.x - d.x) * (c.y - a.y) - c.x
* (b.x - a.x) * (c.y - d.y) + a.x * (b.y - a.y) * (c.x - d.x))
/ ((b.y - a.y) * (c.x - d.x) - (b.x - a.x) * (c.y - d.y));

intersection.y = ((b.y - a.y) * (c.y - d.y) * (c.x - a.x) - c.y
* (b.y - a.y) * (c.x - d.x) + a.y * (b.x - a.x) * (c.y - d.y))
/ ((b.x - a.x) * (c.y - d.y) - (b.y - a.y) * (c.x - d.x));

intersection.x = intersection.x.toFixed(11);//四舍五入为指定位数
intersection.y = intersection.y.toFixed(12);

if ((intersection.x - a.x) * (intersection.x - b.x) <= 0
&& (intersection.x - c.x) * (intersection.x - d.x) <= 0
&& (intersection.y - a.y) * (intersection.y - b.y) <= 0
&& (intersection.y - c.y) * (intersection.y - d.y) <= 0) {
flag = true; // '相交 否则'相交但不在线段上
} else if (c.x == d.x && c.y != d.y && a.y == b.y && a.x != b.x) { // 直角由内向外
flag = true;
} else if (a.x == d.x && a.y != d.y && b.y == c.y && b.x != c.x) { // 直角由外向内
flag = true;
} else if (a.x == b.x && a.y != b.y || a.y == b.y && a.x != b.x) { // 锐角外边平信个,且有一边两端点某坐标在同一坐标
flag = true;
}
return flag;
};

0 0
原创粉丝点击