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

如何使用Canvas 2D绘制箭头头部向下的垂直箭头

解决方案

要实现头部向下的垂直箭头,只需调整drawArrow函数的调用参数,让箭头路径的起点在上、终点在下即可——原函数的箭头始终绘制在路径的终点(tox, toy)位置。

修正后的完整代码

<!DOCTYPE html>
<html>
<body>
  <canvas id="c" width="500" height="500" style="border:1px solid grey"></canvas>

  <script>
    const ctx = document.getElementById("c").getContext("2d");
    // 绘制头部向上的箭头(原效果)
    drawArrow(ctx, 300, 300, 300, 200);
    // 绘制头部向下的箭头(目标效果)
    drawArrow(ctx, 300, 200, 300, 300);
    
    function drawArrow(context, fromx, fromy, tox, toy) {
      const headlen = 10; // 箭头头部长度(像素)
      // 计算从起点到终点的方向角度
      const angle = Math.atan2(toy - fromy, tox - fromx);
      
      context.beginPath();
      // 绘制箭杆
      context.moveTo(fromx, fromy);
      context.lineTo(tox, toy);
      // 绘制箭头左侧斜线
      context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6));
      // 回到箭头顶点,绘制右侧斜线
      context.moveTo(tox, toy);
      context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6));
      context.stroke();
    }
  </script>
</body>
</html>

原理说明

原函数的核心逻辑:

  1. 通过Math.atan2(toy - fromy, tox - fromx)计算从起点到终点的方向角度
  2. 基于该角度向左右各偏移30°(Math.PI/6),绘制箭头头部的两条斜线,形成箭头形状

当把起点设为(300,200)、终点设为(300,300)时:

  • 方向角度变为垂直向下(Math.PI/2)
  • 箭头头部的两条斜线会自动调整为向下张开的形状,匹配目标效果

效果说明

  • 头部向上的箭头:从画布下方(300,300)指向上方(300,200),箭头头部朝上
  • 头部向下的箭头:从画布上方(300,200)指向下方(300,300),箭头头部朝下

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:12:28