使用SVG实现进度条
主要使用了svg的两个属性:
stroke-dasharray:通过数组值创建虚线,可填单个或多个值
stroke-dasharray = '10' // 表示生成长度为10、间隔为10的重复虚线 stroke-dasharray = '10, 5' // 表示生成长度为10、间隔为5的重复虚线 stroke-dasharray = '10,5,15' // 表示生成长度为10、间隔为5、长度为15,然后间隔为10、长度为5、间隔为15的重复虚线
stroke-dashoffset:虚线偏移量
stroke-dashoffset = '10' // 虚线整体向左偏移10个单位 storke-dashoffset = '-10' // 虚线整体向右偏移10个单位
主要实现代码如下:
<svg width="300" height="300"> <line x1="10" y1="10" x2="260" y2="10" stroke="#F2F2F2" strokeWidth="15"></line> <!-- 进度条底图,这里为了简便画了一条直线,可自行替换成需要的svg路径 --> <line x1="10" y1="10" x2="260" y2="10" stroke="#1890FF" strokeWidth="15" ref={pathRef}></line> <!-- 进度条填充图,与底图路径一致,填充色调整为所需进度颜色即可 --> </svg>
const len = pathRef.current.getTotalLength(); // 通过pathRef获取到填充图的长度,js可给标签设置id、通过id获取到对应dom pathRef.current.style.strokeDasharray = len; pathRef.current.style.strokeDashoffset = len - len * (percent / 100); // percent为对应进度
效果如下: