话不多说,直接上代码~~~
<canvas id="canvasId" width="400" height="400" style="border: 1px solid #ccc;"></canvas>
1
window.onload = function(){
var cavParam = {};
cavParam.canvas = document.getElementById("canvasId");
cavParam.ctx = cavParam.canvas.getContext('2d');
drawLineArrow(cavParam, 100, 300, 200, 200, "#a3a3a3");
}
/**
* 绘制带有箭头的直线
* @param cavParam canvas画布变量
* @param fromX/fromY 起点坐标
* @param toX/toY 终点坐标
* @param color 线与箭头颜色
**/
function drawLineArrow(cavParam, fromX, fromY, toX, toY, color) {
var headlen = 10;//自定义箭头线的长度
var theta = 45;//自定义箭头线与直线的夹角,个人觉得45°刚刚好
var arrowX, arrowY;//箭头线终点坐标
// 计算各角度和对应的箭头终点坐标
var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI;
var angle1 = (angle + theta) * Math.PI / 180;
var angle2 = (angle - theta) * Math.PI / 180;
var topX = headlen * Math.cos(angle1);
var topY = headlen * Math.sin(angle1);
var botX = headlen * Math.cos(angle2);
var botY = headlen * Math.sin(angle2);
cavParam.ctx.beginPath();
//画直线
cavParam.ctx.moveTo(fromX, fromY);
cavParam.ctx.lineTo(toX, toY);
arrowX = toX + topX;
arrowY = toY + topY;
//画上边箭头线
cavParam.ctx.moveTo(arrowX, arrowY);
cavParam.ctx.lineTo(toX, toY);
arrowX = toX + botX;
arrowY = toY + botY;
//画下边箭头线
cavParam.ctx.lineTo(arrowX, arrowY);
cavParam.ctx.strokeStyle = color;
cavParam.ctx.stroke();
}