d3.js——箭头的绘制

首先我们要明白如何在svg中进行箭头的绘制:

先写一对<defs>,里面再写一对<marker>,其中marker的属性意义为:

viewBox坐标系的区域
refX, refY在 viewBox 内的基准点,绘制时此点在直线端点上(要注意大小写)
markerUnits标识大小的基准,有两个值:strokeWidth(线的宽度)和userSpaceOnUse(图形最前端的大小)
markerWidth, markerHeight标识的大小
orient绘制方向,可设定为:auto(自动确认方向)和 角度值
id标识的id号
然后,我们利用d3.js来进行箭头的绘制就清楚多了:

//添加defs标签
var defs = svg.append("defs");
//添加marker标签及其属性
var arrowMarker = defs.append("marker")
    .attr("id","arrow")
    .attr("markerUnits","strokeWidth")
    .attr("markerWidth",12)
    .attr("markerHeight",12)
    .attr("viewBox","0 0 12 12")
    .attr("refX",6)
    .attr("refY",6)
    .attr("orient","auto")
//绘制直线箭头
var arrow_path = "M2,2 L10,6 L2,10 L6,6 L2,2";
arrowMarker.append("path")
    .attr("d",arrow_path)
    .attr("fill","#000")
//绘制直线
var line = svg.append("line")
    .attr("x1",50)
    .attr("y1",50)
    .attr("x2",200)
    .attr("y2",400)
    .attr("stroke","red")
    .attr("stroke-width",2)
    .attr("marker-start","url(#arrow)")
    .attr("marker-end","url(#arrow)")
//绘制曲线箭头
var curve_path = "M20,70 T80,100 T160,80 T200,90";
var curve = svg.append("path")
    .attr("d",curve_path)
    .attr("fill","white")
    .attr("stroke","red")
    .attr("stroke-width",2)
    .attr("marker-start","url(#arrow)")
    .attr("marker-mid","url(#arrow)")
    .attr("marker-end","url(#arrow)");

在不同的位置绘制的属性如下:

  • marker-start :路径起点处
  • marker-mid:路径中间端点处(必须是 path 中间出现的点)
  • marker-end :路径终点处
绘制结果如下:






相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页