js 实现箭头图形
使用 Canvas 绘制箭头
通过 HTML5 Canvas 的路径绘制功能可以灵活实现箭头图形。以下是一个完整示例:
<canvas id="arrowCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById('arrowCanvas');
const ctx = canvas.getContext('2d');
function drawArrow(x1, y1, x2, y2, arrowSize) {
// 绘制线段
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
// 计算箭头角度
const angle = Math.atan2(y2 - y1, x2 - x1);
// 绘制箭头头部
ctx.beginPath();
ctx.moveTo(x2, y2);
ctx.lineTo(
x2 - arrowSize * Math.cos(angle - Math.PI / 6),
y2 - arrowSize * Math.sin(angle - Math.PI / 6)
);
ctx.lineTo(
x2 - arrowSize * Math.cos(angle + Math.PI / 6),
y2 - arrowSize * Math.sin(angle + Math.PI / 6)
);
ctx.closePath();
ctx.fill();
}
drawArrow(20, 50, 180, 50, 15);
</script>
使用 SVG 绘制箭头
SVG 的路径语法(path)可以精确控制箭头形状:
<svg width="200" height="100">
<path d="M20,50 L180,50 M180,50 L160,35 M180,50 L160,65"
stroke="black"
fill="none"
stroke-width="2"/>
</svg>
使用 CSS 伪元素创建箭头
纯 CSS 方案适合简单的 UI 箭头指示器:
<div class="arrow"></div>
<style>
.arrow {
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 20px solid #000;
position: relative;
}
.arrow::after {
content: '';
position: absolute;
left: -10px;
top: 5px;
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 15px solid #000;
}
</style>
使用 Unicode 箭头符号
最简单的文本方案(适用于不需要自定义样式的情况):
<div style="font-size: 24px;">→ ← ↑ ↓ ↖ ↗ ↘ ↙</div>
使用第三方库
使用流行的图形库如 Konva.js 可以更方便地实现复杂箭头:

<script src="https://unpkg.com/konva@8/konva.min.js"></script>
<div id="container"></div>
<script>
const stage = new Konva.Stage({
container: 'container',
width: 200,
height: 100
});
const layer = new Konva.Layer();
const arrow = new Konva.Arrow({
points: [20, 50, 180, 50],
pointerLength: 10,
pointerWidth: 10,
fill: 'black',
stroke: 'black',
strokeWidth: 2
});
layer.add(arrow);
stage.add(layer);
</script>
每种方法适用于不同场景:Canvas 适合动态图形,SVG 适合矢量图形,CSS 适合 UI 元素,Unicode 适合简单文本指示,第三方库适合复杂交互场景。






