实现效果图:
svg相关知识
这里只介绍本次用到的元素,更多详情:SVG:可缩放矢量图形
- defs:定义需要重复利用的图形元素
- linearGradient:定义线性渐变,用来图形元素的填充或描边使用
- stop:元素或者元素的子元素,用来描述渐变色的坡度
- circle:基于圆心和半径创建圆形
- cx:定义中心点的x坐标
- cy:定义中心点的y坐标
- r:定义圆的半径
- fill:(对于形状元素)用来定义内部颜色
- stroke:图形外轮廓颜色
- stroke-width:外轮廓宽度
- stroke-dasharray:描边的点划线的图案范式(线段,直线。。。)
- stroke-linecap:开放自路径两端的形状(平角,圆角)
- transform:用来设置动画(非svg属性)
实现代码
1. 定义一个可复用的渐变色
<defs>
<linearGradient id="color">
<stop offset="0%" stop-color="#229453"/>
<stop offset="50%" stop-color="#66c18c"/>
<stop offset="100%" stop-color="#b9dec9"/>
</linearGradient>
</defs>
2. 增加一个外圈的圆,用来包住进度条(旋转整个圆,使缺口朝下)
<circle cx='160' cy='160' r='140' stroke='#999999' stroke-width="20" fill="none" stroke-dasharray="659,300" stroke-linecap="round" transform="rotate(135, 160, 160)"></circle>
3. 增加一个内部的圆,当进度条背景
<circle cx='160' cy='160' r='140' stroke='#ffffff' stroke-width="10" fill="none" stroke-dasharray="659,300" stroke-linecap="round" transform="rotate(135, 160, 160)"></circle>
4. 增加进度条的圆(动画是为了有进度条移动的效果)
<circle id="circle" cx='160' cy='160' r='140' stroke='url(#color)' stroke-width="10" fill="none" style="stroke-dasharray: 0,900; transition: stroke-dasharray 2s" stroke-linecap="round" transform="rotate(135, 160, 160)"></circle>
5. 写一点js代码来改变进度条长度
const circle = document.getElementById('circle')
setTimeout(()=> {
circle.style.strokeDasharray = '600,500'
}, 2000)
完整代码
<div>
<svg style="background: #ffffff" width="320" height="320" viewBox="0 0 320 320">
<defs>
<linearGradient id="color">
<stop offset="0%" stop-color="#229453"/>
<stop offset="50%" stop-color="#66c18c"/>
<stop offset="100%" stop-color="#b9dec9"/>
</linearGradient>
</defs>
<circle cx='160' cy='160' r='140' stroke='#999999' stroke-width="20" fill="none" stroke-dasharray="659,300" stroke-linecap="round" transform="rotate(135, 160, 160)"></circle>
<circle cx='160' cy='160' r='140' stroke='#ffffff' stroke-width="10" fill="none" stroke-dasharray="659,300" stroke-linecap="round" transform="rotate(135, 160, 160)"></circle>
<circle id="circle" cx='160' cy='160' r='140' stroke='url(#color)' stroke-width="10" fill="none" style="stroke-dasharray: 0,900; transition: stroke-dasharray 2s" stroke-linecap="round" transform="rotate(135, 160, 160)"></circle>
</svg>
</div>
const circle = document.getElementById('circle')
setTimeout(()=> {
circle.style.strokeDasharray = '600,500'
}, 2000)