Test if two lines intersect - JavaScript function

前端 未结 10 1550
谎友^
谎友^ 2020-12-02 09:08

I\'ve tried searching for a javascript function that will detect if two lines intersect each other.

The function will take the x,y values of both the start end point

10条回答
  •  萌比男神i
    2020-12-02 10:00

    For all folks who would like to have a solutions ready for coldfusion, here is what I adapted from http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/awt/geom/Line2D.java#Line2D.linesIntersect%28double%2Cdouble%2Cdouble%2Cdouble%2Cdouble%2Cdouble%2Cdouble%2Cdouble%29

    the imporants functions are ccw and linesIntersect from java.awt.geom.Line2D and I wrote them into coldfusion, so here we go:

    
    
    
    
    
    
    
    
        
        x2 = x2 - x1;
        y2 = y2 - y1;
        px = px - x1;
        py = py - y1;
        ccw = (px * y2) - (py * x2);
        if (ccw EQ 0) {
            // The point is colinear, classify based on which side of
            // the segment the point falls on.  We can calculate a
            // relative value using the projection of px,py onto the
            // segment - a negative value indicates the point projects
            // outside of the segment in the direction of the particular
            // endpoint used as the origin for the projection.
            ccw = (px * x2) + (py * y2);
            if (ccw GT 0) {
                // Reverse the projection to be relative to the original x2,y2
                // x2 and y2 are simply negated.
                // px and py need to have (x2 - x1) or (y2 - y1) subtracted
                //    from them (based on the original values)
                // Since we really want to get a positive answer when the
                 //    point is "beyond (x2,y2)", then we want to calculate
                //    the inverse anyway - thus we leave x2 & y2 negated.       
                px = px - x2;
                py = py - y2;
                ccw = (px * x2) + (py * y2);
                if (ccw LT 0) {
                    ccw = 0;
                    }
            }
        }
        if (ccw LT 0) {
            ret = -1;
        }
        else if (ccw GT 0) {
            ret = 1;
        }
        else {
            ret = 0;
        }   
         
        
    
    
    
    
    
    
    
    
    
    
    
    
        
        a1 = relativeCCW(x1, y1, x2, y2, x3, y3);
        a2 = relativeCCW(x1, y1, x2, y2, x4, y4);
        a3 = relativeCCW(x3, y3, x4, y4, x1, y1);
        a4 = relativeCCW(x3, y3, x4, y4, x2, y2);
        aa = ((relativeCCW(x1, y1, x2, y2, x3, y3) * relativeCCW(x1, y1, x2, y2, x4, y4) LTE 0)
                && (relativeCCW(x3, y3, x4, y4, x1, y1) * relativeCCW(x3, y3, x4, y4, x2, y2) LTE 0));
        
     
    
    

    I hope this can help for adapting to other laguages?

提交回复
热议问题