环形进度条 #SVG #D3.js

2018-11-14 04:01

D3框架学习

实现环形进度条,效果如下图,代码见codePen


可以调整参数

var data= [{
process:0, // 进度 100为满
lineWidth:20, // 进度条宽
radius:100, // 圆形进度条中心线的半径
fill:'#1c7abc', // 进度条颜色
stroke:'white', // 进度条边框颜色
strokeWidth:2, // 进度条边框宽度
x:width/2, // 圆形进度条的中心坐标x
y:height/2,// 圆形进度条的中心坐标y
startAngle:-Math.PI /2// 起始角度,0为3点钟方向
}];

d3的数据绑定,用data()传入输入数组,画圆的时候可以批量画。

d3上来先selectAll虽然没有,表示后面操作的基数,enter表示若有新增数据,会新增到dom里面。更新数据需要自己刷新展示。和vue这种数据绑定不一样,不是改数据就会触发视图刷新,修改数据后,需要调用变更的方法。比如这个path改了,就使用 path.attr("d", draw)重新更新进度。

SVG学习部分

主要是path,d的画法,用4条曲线实现环形进度条。

path里面的d的M表述移动到点不绘制线,L表示画线,A表示画圆圆形等,最后Z表示闭合曲线。具体参考MDN说明

这里A的参数和D3里面的path.arc参数不同,看一下arc的官方说明。

# path.arc(x, y, radius, startAngle, endAngle[, anticlockwise]) <>

Draws a circular arc segment with the specified center ⟨x, y⟩, radius, startAngle and endAngle. If anticlockwise is true, the arc is drawn in the anticlockwise direction; otherwise, it is drawn in the clockwise direction. If the current point is not equal to the starting point of the arc, a straight line is drawn from the current point to the start of the arc. Equivalent to context.arc and uses SVG’s elliptical arc curve commands.


就是说,前两个表示这段圆弧的中心点坐标,第三个表示这段圆弧的半径长;
第四和第五表示开始和结束的弧度,经过实践0为3点钟方向,Math.PI表示9点钟方向。
最后一个若写了true,表示画大圆还是小圆。