js计算点到直线的距离并使用canvas可视化

使用方程计算

result.png

<!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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值