I want to determine if a click is made between to points and roughly on the line segment that connects those two points.
My question is similar to How can you determine a point is between two other points on a line segment? but it defers in two points:
- Im working in javascript and coordinates are in integers (pixels)
- The point do not have to be exactly on the line segment. A tolerance is needed.
The following code is adapted from this answer, but I dont know how to insert a tolerance around the line segment
a
and b
are the end points of the line segment and c
is the clicked point. I want to check if c
is between a
and b
and roughly on the segment that connects a
and b
PencilTool.prototype._isBetween = function(a,b,c){
//test if a, b and c are aligned
var crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y);
if(Math.abs(crossproduct) !== 0){ return false; }
var dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if(dotproduct < 0){ return false }
var squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y);
if(dotproduct > squaredlengthba){ return false; }
return true;
}