<!--
// from
// http://www.gamedev.net/topic/444154-closest-point-on-a-line/
 
function getClosestPoint(A:*, B:*, P:*, segmentClamp:Boolean=true):Point {
    var AP:Point = new Point(P.x - A.x, P.y - A.y),
        AB:Point = new Point(B.x - A.x, B.y - A.y);
    var ab2:Number=AB.x*AB.x+AB.y*AB.y;
    var ap_ab:Number=AP.x*AB.x+AP.y*AB.y;
    var t:Number=ap_ab/ab2;
    if (segmentClamp) {
        if (t<0.0) {
            t=0.0;
        } else if (t> 1.0) {
            t=1.0;
        }
 
    }
    return new Point(A.x + AB.x * t, A.y + AB.y * t);
}
 
 
var point:Sprite = Sprite(addChild(new Sprite()));
point.x = 50;
point.y = 50;
with(point.graphics) beginFill(0), drawCircle(0,0, 3);
 
var line:MovieClip = MovieClip(addChild(new MovieClip()));
line.a = new Point(20, 100);
line.b = new Point(300, 60);
with(line.graphics) lineStyle(0), moveTo(line.a.x, line.a.y), lineTo(line.b.x, line.b.y);
 
var closestPoint:Point = getClosestPoint(line.a, line.b, point);
 
var closest:Sprite = Sprite(addChild(new Sprite()));
closest.x = closestPoint.x;
closest.y = closestPoint.y;
with(closest.graphics) beginFill(0xFF0000), drawCircle(0,0, 3);
-->
* {
  margin: 0; padding: 0;
}
let canvas = document.createElement('canvas'), 
    c = canvas.getContext('2d'), 
    SIZE = 400;

canvas.width = SIZE;
canvas.height = SIZE;
document.body.appendChild(canvas);

function clear() {
  c.fillStyle = 'gray';
  c.fillRect(0, 0, canvas.width, canvas.height);
}

// http://www.gamedev.net/topic/444154-closest-point-on-a-line/
function getClosestPoint(a, b, p, segmentClamp = true) {
    let ap = { x: p.x - a.x, y: p.y - a.y },
        ab = { x: b.x - a.x, y: b.y - a.y },
        ab2 = ab.x * ab.x + ab.y * ab.y,
        apab = ap.x * ab.x + ap.y * ab.y,
        t = apab / ab2;
  
    if (segmentClamp) {
        if (t < 0.0) {
          t = 0.0;
        } else if (t > 1.0) {
            t = 1.0;
        }
 
    }
    return { x: a.x + ab.x * t, y: a.y + ab.y * t};
}

clear();

// point
let pnt = { x: 50, y: 50 };
c.fillStyle = 'red';
c.beginPath(); c.arc(pnt.x, pnt.y, 4, 0, Math.PI * 2, true);
c.fill();

// line
let a = { x: 20, y: 100 };
let b = { x: 300, y: 60 };
c.beginPath();
c.moveTo(a.x, a.y);
c.lineTo(b.x, b.y);
c.stroke();

// closest point
let closestPoint = getClosestPoint(a, b, pnt);
c.fillStyle = 'black';
c.beginPath(); c.arc(
  closestPoint.x, closestPoint.y, 4, 0, Math.PI * 2, true
);
c.fill();
 

View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.