var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var lineStart={x:50,y:50};
var lineEnd={x:250,y:250};
var cr=15;
draw({x:-20,y:-20},'green');
$("#canvas").mousemove(function(e){handleMouseMove(e);});
function draw(pt,fill){
ctx.clearRect(0,0,cw,ch);
ctx.beginPath();
ctx.moveTo(lineStart.x,lineStart.y);
ctx.lineTo(lineEnd.x,lineEnd.y);
ctx.strokeStyle='black';
ctx.stroke();
ctx.beginPath();
ctx.arc(pt.x,pt.y,5,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=fill;
ctx.fill();
}
function calcClosestPtOnSegment(x0,y0,x1,y1,cx,cy,cr){
var dx=cx-x0;
var dy=cy-y0;
var dxx=x1-x0;
var dyy=y1-y0;
var t=(dx*dxx+dy*dyy)/(dxx*dxx+dyy*dyy);
var x=x0+dxx*t;
var y=y0+dyy*t;
if(t<0){x=x0;y=y0;}
if(t>1){x=x1;y=y1;}
return({
x:x, y:y,
isColliding:((cx-x)*(cx-x)+(cy-y)*(cy-y)) < cr*cr,
isOnSegment:(t>=0 && t<=1),
});
}
function handleMouseMove(e){
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
var p=calcClosestPtOnSegment(
lineStart.x,lineStart.y,lineEnd.x,lineEnd.y,
mouseX,mouseY,cr);
var fill=(p.isOnSegment)?'green':'red';
draw(p,fill);
ctx.beginPath();
ctx.arc(mouseX,mouseY,cr,0,Math.PI*2);
ctx.closePath();
ctx.strokeStyle=p.isColliding?'green':'blue';
ctx.stroke();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Move mouse to see closest point on angled line segment.<br>Closest point is green (or red if beyond segment) </h4>
<canvas id="canvas" width=300 height=300></canvas>
mouseDown
处理程序中添加myPath.add(event.point)
也将允许开始绘制直线。如果我加上这个,你介意吗? - nicholaswmin