For a PaperJS project I was looking for a function where I would pass three points. Two points that form the line and One point from which I have to find the nearest point on the line. And in Return I will get the point on the line which is closest to that point.

On paperJS we already have a simple solution in place which can let us do this called. **getNearestLocation(point) and we can use it on any item. **

But in my project I do not want to create an item which will be displayed to use this. So I wanted just a simple function which just takes points as an input and with some research I exactly got the same.

```
function findNearest( p, a, b )
{
var atob = { x: b.x - a.x, y: b.y - a.y };
var atop = { x: p.x - a.x, y: p.y - a.y };
var len = atob.x * atob.x + atob.y * atob.y;
var dot = atop.x * atob.x + atop.y * atob.y;
var t = Math.min( 1, Math.max( 0, dot / len ) );
dot = ( b.x - a.x ) * ( p.y - a.y ) - ( b.y - a.y ) * ( p.x - a.x );
return new Point(a.x + atob.x * t,a.y + atob.y * t);
}
```

This function returned exactly what I was looking for.

You can see a running implementation of the same in the JSFiddle example below.