<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.0/paper-full.min.js"></script>
<div id="container">
<h1>Finding closest Point on line from another point</h1>
<p>Please move the mouse to see red dots react. </p>
<canvas id="myCanvas" width="500" height="300"></canvas>
</div>
<hr>
Created by <a href="http://www.iamshishir.com">Shishir Raven</a> for <a href="http://www.thewebfort.com">Webfort Technologies</a>
<br>
Hire Me or hire a team for your projects at very affordable rates.
JavaScript
var canvas = document.getElementById("myCanvas");
paper.install(window);
paper.setup(canvas);
var point1 = new Point(1,1);
var point2 = new Point(200,200);
var distancePoint = new Point(200,100);
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);
}
var LineObject = function(point1,point2)
{
this.point1 = point1;
this.point2 = point2;
var lineToDraw = new Path(point1,point2);
lineToDraw.strokeColor = 'black';
this.dPoint = new Path.Circle({
center: distancePoint,
radius: 10,
fillColor: 'black'
});
this.pointOnLine = new Path.Circle({
center: distancePoint,
radius: 10,
fillColor: 'red'
});
this.findTheNearest= function(point)
{
this.pointOnLine.position=findNearest(point , this.point1, this.point2);
}
}
LineObject.prototype.track = function(point) {
this.dPoint.position = point ;
this.findTheNearest(point);
}
var testline = new LineObject(point1, point2);
var testline2 = new LineObject(new Point(500,10), new Point(300,200));
view.onMouseMove = function(event) {
testline.track(event.point);
testline2.track(event.point);
};
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.