确定一个点是否在线段上(或足够接近)

时间:2015-12-26 19:06:49

标签: javascript geometry

我想确定鼠标点击点是否位于SVG折线上。我发现this Python code确定一个点是否位于另外两个点之间,并在JavaScript中重新实现。

function isOnLine(xp, yp, x1, y1, x2, y2){

    var p = new Point(x, y);
    var epsilon = 0.01;

    var crossProduct = (yp - y1) * (x2 - x1) - (xp - x1) * (y2 - y1);
    if(Math.abs(crossProduct) > epsilon)
        return false;
    var dotProduct = (xp - x1) * (x2 - x1) + (yp - y1)*(y2 - y1);
    if(dotProduct < 0)
        return false;
    var squaredLengthBA = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1);
    if(dotProduct > squaredLengthBA)
        return false;

    return true;
}

但是它没有按照我想要的方式工作,因为我永远不会在行上获得鼠标指针 。因此,我需要像“虚构的粗线”这样的东西来获得一些误差:

enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

cross product除以线的长度,得出点与线的距离。所以只需将其与某个阈值进行比较:

function isOnLine (xp, yp, x1, y1, x2, y2, maxDistance) {
    var dxL = x2 - x1, dyL = y2 - y1;  // line: vector from (x1,y1) to (x2,y2)
    var dxP = xp - x1, dyP = yp - y1;  // point: vector from (x1,y1) to (xp,yp)

    var squareLen = dxL * dxL + dyL * dyL;  // squared length of line
    var dotProd   = dxP * dxL + dyP * dyL;  // squared distance of point from (x1,y1) along line
    var crossProd = dyP * dxL - dxP * dyL;  // area of parallelogram defined by line and point

    // perpendicular distance of point from line
    var distance = Math.abs(crossProd) / Math.sqrt(squareLen);

    return (distance <= maxDistance && dotProd >= 0 && dotProd <= squareLen);
}

Ps。上面的代码实际上会将线段扩展为一个框,方法是将其加宽maxDistance,并接受该框中的任何点击。如果您要将其应用于折线(即多个线段以端对端方式连接),您可能会发现这些框之间存在间隙,其中两个线段以一定角度相交:

Illustration of expanded polyline with gaps

解决这个问题的一种简单而自然的方法是接受来自端点的半径maxDistance内任意位置的任何点击,基本上用(半)圆形端盖填充虚构框:

Illustration of expanded polyline with end caps joining segments

以下是实现此目的的一种方法:

function isOnLineWithEndCaps (xp, yp, x1, y1, x2, y2, maxDistance) {
    var dxL = x2 - x1, dyL = y2 - y1;  // line: vector from (x1,y1) to (x2,y2)
    var dxP = xp - x1, dyP = yp - y1;  // point: vector from (x1,y1) to (xp,yp)
    var dxQ = xp - x2, dyQ = yp - y2;  // extra: vector from (x2,y2) to (xp,yp)

    var squareLen = dxL * dxL + dyL * dyL;  // squared length of line
    var dotProd   = dxP * dxL + dyP * dyL;  // squared distance of point from (x1,y1) along line
    var crossProd = dyP * dxL - dxP * dyL;  // area of parallelogram defined by line and point

    // perpendicular distance of point from line
    var distance = Math.abs(crossProd) / Math.sqrt(squareLen);

    // distance of (xp,yp) from (x1,y1) and (x2,y2)
    var distFromEnd1 = Math.sqrt(dxP * dxP + dyP * dyP);
    var distFromEnd2 = Math.sqrt(dxQ * dxQ + dyQ * dyQ);

    // if the point lies beyond the ends of the line, check if
    // it's within maxDistance of the closest end point
    if (dotProd < 0) return distFromEnd1 <= maxDistance;
    if (dotProd > squareLen) return distFromEnd2 <= maxDistance;

    // else check if it's within maxDistance of the line
    return distance <= maxDistance;
}