simplify.js
function getSqSegDist(p, p1, p2) {

    var x = p1.x,
        y = p1.y,
        dx = p2.x - x,
        dy = p2.y - y;

    if (dx !== 0 || dy !== 0) {

        var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);

        if (t > 1) {
            x = p2.x;
            y = p2.y;

        } else if (t > 0) {
            x += dx * t;
            y += dy * t;
        }
    }

    dx = p.x - x;
    dy = p.y - y;

    return dx * dx + dy * dy;
}
function getSqSegDist(p, p1, p2) {

    var x = p1.x,
        y = p1.y,
        dx = p2.x - x,
        dy = p2.y - y;

    if (dx !== 0 || dy !== 0) {

        var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);

        if (t > 1) {
            x = p2.x;
            y = p2.y;

        } else if (t > 0) {
            x += dx * t;
            y += dy * t;
        }
    }

    dx = p.x - x;
    dy = p.y - y;

    return dx * dx + dy * dy;
}
function getSqSegDist ( p , p1 , p2 ) { var x = p1 . x , y = p1 . y , dx = p2 . x - x , dy = p2 . y - y ; if ( dx !== 0 || dy !== 0 ) { var t = ( ( p . x - x ) * dx + ( p . y - y ) * dy ) / ( dx * dx + dy * dy ) ; if ( t > 1 ) { x = p2 . x ; y = p2 . y ; } else if ( t > 0 ) { x += dx * t ; y += dy * t ; } } dx = p . x - x ; dy = p . y - y ; return dx * dx + dy * dy ; }
square distance from a point to a segment
square distance from a point to a segment