# 有一段算法代码不太理解，求解释

0

``````var line = { x0: 50, y0: 50, x1: 100, y1: 100 };

//x,y为传入的鼠标坐标
function linepointNearestMouse(line, x, y) {
//线性插值
lerp = function(a, b, x) {
return (a + x * (b - a));
};
var dx = line.x1 - line.x0;
var dy = line.y1 - line.y0;

//这里的t是怎么计算出来的，用到什么公式？
var t = ((x - line.x0) * dx + (y - line.y0) * dy) / (dx * dx + dy * dy);

var lineX = lerp(line.x0, line.x1, t);
var lineY = lerp(line.y0, line.y1, t);
return ({
x: lineX,
y: lineY
});
};

function handleMousemove(e) {
e.preventDefault();
e.stopPropagation();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);

//如果鼠标不在线段的矩形范围内则忽略
if (mouseX < line.x0 || mouseX > line.x1) {
\$hit.text("Outside");
draw(line);
return;
}
//为什么这里的linepoint就是直线上的点坐标？
var linepoint = linepointNearestMouse(line, mouseX, mouseY);
var dx = mouseX - linepoint.x;
var dy = mouseY - linepoint.y;
var distance = Math.abs(Math.sqrt(dx * dx + dy * dy));

//如果当前鼠标位置与linepoint的距离小于5，则绘制小红点
if (distance < 5) {
\$hit.text("Inside the line");
draw(line, mouseX, mouseY, linepoint.x, linepoint.y);
} else {
\$hit.text("Outside");
draw(line);
}
}``````

1

@逐影: 你确定你这个题目没什么错误嘛，为什么给的两个点是(50, 50), (100, 100)但是上图显示的应该是(50, 100)和(100, 50) 才对

@编程小白-郭旭: 大佬太厉害了，推导的过程非常严谨👍👍👍，今天弄了一天，就是没有想到

``l = tL``

0

您需要登录以后才能回答，未注册用户请先注册