Canvas的 CanvasRenderingContext2D
对象中是没有提供绘制箭头的方法,也就是说,如果我们需要在Canvas中绘制箭头是需要自己封装函数来处理的。
封装函数
// ctx:Canvas绘图环境
// fromX, fromY:起点坐标(也可以换成 p1 ,只不过它是一个数组)
// toX, toY:终点坐标 (也可以换成 p2 ,只不过它是一个数组)
// theta:三角斜边一直线夹角
// headlen:三角斜边长度
// width:箭头线宽度
// color:箭头颜色
function drawArrow(ctx, fromX, fromY, toX, toY,theta = 30,headlen = 10,width = 1,color = '#333') {
var theta = theta || 30,
headlen = headlen || 10,
width = width || 1,
color = color || '#000',
angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI,
angle1 = (angle + theta) * Math.PI / 180,
angle2 = (angle - theta) * Math.PI / 180,
topX = headlen * Math.cos(angle1),
topY = headlen * Math.sin(angle1),
botX = headlen * Math.cos(angle2),
botY = headlen * Math.sin(angle2);
ctx.save();
ctx.beginPath();
var arrowX, arrowY;
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
arrowX = toX + topX;
arrowY = toY + topY;
ctx.moveTo(arrowX, arrowY);
ctx.lineTo(toX, toY);
arrowX = toX + botX;
arrowY = toY + botY;
ctx.lineTo(arrowX, arrowY);
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.stroke();
ctx.restore();
}
调用一下
var canvas = document.querySelector('#mycanvas');
var ctx = canvas.getContext('2d');
drawArrow(ctx, 150, 100, 350,100);
效果图:
双向箭头:
function drawArrow(ctx, fromX, fromY, toX, toY,theta,headlen,width,color) {
var theta = theta || 30,
headlen = headlen || 10,
width = width || 1,
color = color || '#000',
angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI,
angle1 = (angle + theta) * Math.PI / 180,
angle2 = (angle - theta) * Math.PI / 180,
topX = headlen * Math.cos(angle1),
topY = headlen * Math.sin(angle1),
botX = headlen * Math.cos(angle2),
botY = headlen * Math.sin(angle2);
ctx.save();
ctx.beginPath();
var arrowX = fromX - topX,
arrowY = fromY - topY;
ctx.moveTo(arrowX, arrowY);
ctx.lineTo(fromX, fromY);
arrowX = fromX - botX;
arrowY = fromY - botY;
ctx.lineTo(arrowX, arrowY);
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
// Reverse length on the other side
arrowX = toX + topX;
arrowY = toY + topY;
ctx.moveTo(arrowX, arrowY);
ctx.lineTo(toX, toY);
arrowX = toX + botX;
arrowY = toY + botY;
ctx.lineTo(arrowX, arrowY);
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.stroke();
ctx.restore();
}