You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确定线段(x1,y1)-(x2,y2)端点(x2,y2)处箭头的坐标?

计算箭头端点坐标的实用方法

假设你已经有了线段起点(x1, y1)和终点(x2, y2),要在(x2, y2)处画箭头,以下是一步步的计算方法,不用复杂几何知识就能搞定:

核心思路

箭头的两个端点是从(x2, y2)出发,向原线段的两侧对称延伸,且到(x2, y2)的距离相等(也就是在同一个圆上)。我们用向量旋转的方法来计算这两个点,步骤如下:

步骤1:计算原线段的反向单位向量

首先算出从终点指向起点的向量(因为箭头要指向线段的反方向),再把它变成长度为1的单位向量(方便后续调整箭头长度):

import math

# 已知坐标
x1, y1 = 10, 10
x2, y2 = 50, 50
arrow_length = 12  # 箭头的长度(圆的半径,可自行调整)
arrow_angle = 30   # 箭头与原线段的夹角,常用30/45度

# 计算从(x2,y2)指向(x1,y1)的向量
dx = x1 - x2
dy = y1 - y2

# 计算向量长度,避免除以0(如果线段长度为0的话)
segment_length = math.hypot(dx, dy)
if segment_length == 0:
    # 线段长度为0时,随便选两个垂直方向的点
    pt1 = (x2 + arrow_length, y2)
    pt2 = (x2, y2 + arrow_length)
else:
    # 单位向量(长度为1)
    unit_dx = dx / segment_length
    unit_dy = dy / segment_length

步骤2:旋转单位向量得到箭头方向

把上面的单位向量分别旋转+arrow_angle和-arrow_angle,得到两个箭头的方向向量:

# 把角度转换成弧度
theta = math.radians(arrow_angle)

# 旋转+theta度的向量
rot_dx1 = unit_dx * math.cos(theta) - unit_dy * math.sin(theta)
rot_dy1 = unit_dx * math.sin(theta) + unit_dy * math.cos(theta)

# 旋转-theta度的向量
rot_dx2 = unit_dx * math.cos(-theta) - unit_dy * math.sin(-theta)
rot_dy2 = unit_dx * math.sin(-theta) + unit_dy * math.cos(-theta)

步骤3:计算箭头端点坐标

用箭头长度乘以旋转后的向量,再加上(x2, y2)的坐标,就是两个箭头端点:

# 第一个箭头点
pt1 = (x2 + rot_dx1 * arrow_length, y2 + rot_dy1 * arrow_length)
# 第二个箭头点
pt2 = (x2 + rot_dx2 * arrow_length, y2 + rot_dy2 * arrow_length)

实用调整建议

  • arrow_length:可以根据需求调整,比如取原线段长度的1/8到1/10,视觉效果比较自然
  • arrow_angle:30度或45度是最常用的箭头夹角,适配大多数场景
  • 如果线段起点和终点重合,代码里做了特殊处理,避免计算报错

最后你只需要绘制(x2,y2)-pt1和(x2,y2)-pt2这两条线段,就能得到标准的箭头了。

内容的提问来源于stack exchange,提问作者jcro001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 07:55:19