Take the 2-minute tour ×

I have the following code:

Object.defineProperty(LineSegment.prototype,'hasPoint',{ value:
    function (point) {
        if (typeof point != 'object' || !(point instanceof Point)) {
            throw new TypeError('LineSegment.prototype.hasPoint requires a point value.'); }
        var m = (this.y1 - this.y2) / (this.x1 - this.x2);
        return (this.y1 - point.y) / (this.x1 - point.x) == m; }

It works fine for lines, but not line segments. How would I check if the point is out of bounds, and apply it to JavaScript?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

The easiest and fastest answer can only be used if x1 < x2. In that case, the following return statement:

return (this.y1 - point.y) / (this.x1 - point.x) == m && point.x >= this.x1 && point.x <= this.x2;

The first part checks if the point is on the line, the two next conditions check if the x coordinate is between x1 and x2 (inclusive).

Note: if x2 < x1, you can simply add a condition in the constructor to swap the two points. You could also change the point in the form p+q*v (where p is the first point of the line, q the second and v a scalar value, this is only possible if the point is on the line). If v is between 0 and 1 (inclusive), the point is on the line segment.

EDIT: Just a warning, your method won't be very reliable, because of the way computers handle doubles. See the wikipedia page for some examples: http://en.wikipedia.org/wiki/Double_precision

share|improve this answer
Thanks, I ended up using: return ((this.y1 - point.y) / (this.x1 - point.x) == m && ( point.x >= this.x1 && point.x <= this.x2 || point.x <= this.x1 && point.x >= this.x2)) || (this.y1 == point.y && this.x == point.x);, I'll look into something to deal with the float issue later, probably a 9e6 type solution. –  Not a Name Feb 2 '11 at 2:18
add comment

Your Answer


