所以用sin,cos,tan等三角函数则可准确计算出箭头的位置和方向。
这样,箭头的方向就可以自动适应线条的方向,一点都不歪
如图
JS代码
/** * 画带有箭头的直线,箭头在中间 * @param x1 * @param y1 * @param x2 * @param y2 * @returns path */ function drawLineArrow(x1,y1,x2,y2){ var path; var slopy,cosy,siny; var Par=10.0; var x3,y3; slopy=Math.atan2((y1-y2),(x1-x2)); cosy=Math.cos(slopy); siny=Math.sin(slopy); path="M"+x1+","+y1+" L"+x2+","+y2; x3=(Number(x1)+Number(x2))/2; y3=(Number(y1)+Number(y2))/2; path +=" M"+x3+","+y3; path +=" L"+(Number(x3)+Number(Par*cosy-(Par/2.0*siny)))+","+(Number(y3)+Number(Par*siny+(Par/2.0*cosy))); path +=" M"+(Number(x3)+Number(Par*cosy+Par/2.0*siny)+","+ (Number(y3)-Number(Par/2.0*cosy-Par*siny))); path +=" L"+x3+","+y3; return path; }
得到path之后用snap.svg 画出来就好了,
完整的代码,需要用到jquery 和 snap.svg
<svg id="svg" xmlns="http://www.w3.org/2000/svg" version="1.1" width="622px" height="417px"> </svg> <script src="jquery.min.js"></script> <script src="snap.svg-min.js"></script> <script> /** * 画带有箭头的直线,箭头在中间 * @param x1 * @param y1 * @param x2 * @param y2 * @returns path */ function drawLineArrow(x1,y1,x2,y2){ var path; var slopy,cosy,siny; var Par=10.0; var x3,y3; slopy=Math.atan2((y1-y2),(x1-x2)); cosy=Math.cos(slopy); siny=Math.sin(slopy); path="M"+x1+","+y1+" L"+x2+","+y2; x3=(Number(x1)+Number(x2))/2; y3=(Number(y1)+Number(y2))/2; path +=" M"+x3+","+y3; path +=" L"+(Number(x3)+Number(Par*cosy-(Par/2.0*siny)))+","+(Number(y3)+Number(Par*siny+(Par/2.0*cosy))); path +=" M"+(Number(x3)+Number(Par*cosy+Par/2.0*siny)+","+ (Number(y3)-Number(Par/2.0*cosy-Par*siny))); path +=" L"+x3+","+y3; return path; } $(function(){ var svg = Snap("#svg"); var path1 = drawLineArrow(100,120,200,300); svg.paper.path(path1).attr({ stroke: "red", strokeWidth: 2 }); var path2 = drawLineArrow(20,20,20,70); svg.paper.path(path2).attr({ stroke: "blue", strokeWidth: 2 }); var path3 = drawLineArrow(70,30,170,30); svg.paper.path(path3).attr({ stroke: "black", strokeWidth: 2 }); }); </script>