js 实现箭头图形
使用 Canvas 绘制箭头
通过 HTML5 Canvas API 可以灵活绘制自定义箭头图形。以下是一个示例代码,绘制一个带箭头的线段:
function drawArrow(ctx, fromX, fromY, toX, toY, headLength = 10) {
// 绘制线段
ctx.beginPath();
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.stroke();
// 计算箭头角度
const angle = Math.atan2(toY - fromY, toX - fromX);
// 绘制箭头头部
ctx.beginPath();
ctx.moveTo(toX, toY);
ctx.lineTo(
toX - headLength * Math.cos(angle - Math.PI / 6),
toY - headLength * Math.sin(angle - Math.PI / 6)
);
ctx.moveTo(toX, toY);
ctx.lineTo(
toX - headLength * Math.cos(angle + Math.PI / 6),
toY - headLength * Math.sin(angle + Math.PI / 6)
);
ctx.stroke();
}
// 使用示例
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
drawArrow(ctx, 50, 50, 200, 200);
使用 SVG 创建箭头
SVG 是矢量图形的理想选择,可以通过 path 元素创建箭头:

function createSVGArrow(x1, y1, x2, y2, headSize = 10) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', Math.max(x1, x2) + headSize);
svg.setAttribute('height', Math.max(y1, y2) + headSize);
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
// 计算箭头路径
const angle = Math.atan2(y2 - y1, x2 - x1);
const head1 = {
x: x2 - headSize * Math.cos(angle - Math.PI / 6),
y: y2 - headSize * Math.sin(angle - Math.PI / 6)
};
const head2 = {
x: x2 - headSize * Math.cos(angle + Math.PI / 6),
y: y2 - headSize * Math.sin(angle + Math.PI / 6)
};
const d = `M${x1},${y1} L${x2},${y2} L${head1.x},${head1.y} M${x2},${y2} L${head2.x},${head2.y}`;
path.setAttribute('d', d);
path.setAttribute('stroke', 'black');
path.setAttribute('fill', 'none');
svg.appendChild(path);
return svg;
}
// 使用示例
document.body.appendChild(createSVGArrow(50, 50, 200, 200));
使用 CSS 创建简单箭头
对于简单的 UI 箭头,可以使用 CSS 边框技巧:

<style>
.arrow {
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid black;
}
.arrow-right {
transform: rotate(-90deg);
}
</style>
<div class="arrow arrow-right"></div>
使用 Unicode 箭头符号
对于最简单的需求,可以直接使用 Unicode 箭头字符:
console.log('← → ↑ ↓ ↔ ↕ ↖ ↗ ↘ ↙');
使用第三方库
对于复杂需求,可以考虑使用图形库:
// 使用 Konva.js 示例
const stage = new Konva.Stage({ container: 'container', width: 300, height: 300 });
const layer = new Konva.Layer();
const arrow = new Konva.Arrow({
points: [50, 50, 200, 200],
pointerLength: 10,
pointerWidth: 10,
fill: 'black',
stroke: 'black',
strokeWidth: 2
});
layer.add(arrow);
stage.add(layer);
每种方法适用于不同场景:Canvas 适合动态绘图,SVG 适合可缩放矢量图形,CSS 适合简单 UI 元素,Unicode 适合文本环境,第三方库提供更高级功能。






