Point To Line Intersection //JavaScript Repository

Description

Intersection point between a point to a line.
Created: 2005.08.20

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/dot-line-intersection [rev. #1]

dotLineIntersection = function(x, y, x0, y0, x1, y1){
    if(!(x1 - x0))
        return {x: x0, y: y};
    else if(!(y1 - y0))
        return {x: x, y: y0};
    var left, tg = -1 / ((y1 - y0) / (x1 - x0));
    return {x: left = (x1 * (x * tg - y + y0) + x0 * (x * - tg + y - y1)) / (tg * (x1 - x0) + y0 - y1), y: tg * left - tg * x + y};
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

o = dotLineIntersection(0, 1, 0, 0, 1, 1);
alert('y = ' + o.y + '\nx = ' + o.x);

//]]>
</script>

Help

dotLineIntersection(px: Integer, py: Integer, x0: Integer, y0: Integer, x1: Integer, y1: Integer): Object
Returns an object containing two properties (x and y), that specify the intersection point between a line and an imaginary line that passes in the point and it's also perpendicular (makes an angle of 90°) to the same line.
px
x coord of the point
py
y coord of the point
x0
x coord of the line's A point
y0
y coord of the line's A point
x1
x coord of the line's B point
y1
y coord of the line's B point

Rank (Votes: 38)

3.63