使用方程计算
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Distance to Line Visualization</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="600" height="400"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 定义直线的两个点
const linePoint1 = { x: 300, y: 200 };
const linePoint2 = { x: 400, y: 300 };
// 定义点的坐标
const point = { x: 200, y: 200 };
// 计算直线方程的斜率
const slope = (linePoint2.y - linePoint1.y) / (linePoint2.x - linePoint1.x);
// 计算直线方程的截距
const intercept = linePoint1.y - slope * linePoint1.x;
// 绘制直线
ctx.beginPath();
ctx.moveTo(linePoint1.x, linePoint1.y);
ctx.lineTo(linePoint2.x, linePoint2.y);
ctx.strokeStyle = '#00FF00'; // 绿色
ctx.stroke();
// 绘制点
ctx.beginPath();
ctx.arc(point.x, point.y, 5, 0, 2 * Math.PI);
ctx.fillStyle = '#000'; // 黑色
ctx.fill();
// 计算直线外一点在直线方程中的替换值
const m = point.x + slope * point.y;
// 计算交点的 x 坐标
const xIntersection = (m - slope * intercept) / (slope * slope + 1);
// 计算交点的 y 坐标
const yIntersection = slope * xIntersection + intercept;
// 计算点到直线的距离
const distance = Math.sqrt((point.x - xIntersection) ** 2 + (point.y - yIntersection) ** 2);
// 绘制距离线
ctx.setLineDash([5, 5]); // 设置虚线
ctx.beginPath();
ctx.moveTo(point.x, point.y);
ctx.lineTo(xIntersection, yIntersection);
ctx.strokeStyle = '#000'; // 黑色
ctx.stroke();
// 显示距离
ctx.font = '14px Arial';
ctx.fillStyle = '#000'; // 黑色
ctx.fillText('Distance: ' + distance.toFixed(2), point.x + 10, point.y - 10);
</script>
</body>
</html>