svg实现环形进度条
更新时间: 2025-08-06 11:08:55
今天的工作写了这样一个环形进度条,稍微记录一下

# 原理
进度条的原理其实就是circle元素的stroke-dasharray,和stroke-dashoffset属性,这两个属性原本是用来画虚线的,但是虚线足够的长看起来就和进度条没什么两样了。
这个进度条其实就是用几个svg的圆形堆起来的,然后动态计算一下stroke-dasharray和stroke-dashoffset
# 代码实现
我封装成了vue3的组件
<template>
<div class="circle-progress" ref="circleProgress">
<svg v-if="width > 0" :width="width" :height="width" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<!-- 背景圆环 -->
<circle
cx="50" cy="50" r="45"
fill="none"
stroke="#374159"
stroke-width="8"
/>
<!-- 进度圆环(直角末端) -->
<circle
ref="circle"
cx="50" cy="50" r="45"
fill="none"
:stroke="color"
stroke-width="8"
:stroke-dasharray="strokeDasharray"
:stroke-dashoffset="strokeDashoffset"
transform="rotate(-90 50 50)"
/>
<!-- 中心百分比文字背景圆 -->
<circle
cx="50" cy="50" r="36"
fill="#0A1E36"
stroke="#87BAFF33"
stroke-width="1"
/>
<!-- 中心百分比文字 -->
<text
ref="text"
x="50" y="50"
font-family="Arial, sans-serif"
font-size="16"
font-weight="bold"
text-anchor="middle"
dominant-baseline="middle"
fill="white"
>32%</text>
</svg>
</div>
</template>
<script lang="ts" setup>
import {computed, defineProps, ref, onMounted, watch} from "vue";
const props = defineProps({
percent:{
type:[Number, String],
default: 0
},
color:{
type:String,
default:'rgba(96, 157, 255, 1)'
}
})
const circleProgress = ref()
const circle = ref()
const text = ref()
const width = ref(0)
const strokeDasharray = ref(0)
const strokeDashoffset = ref(0)
const color = ref(props.color)
onMounted(() => {
// 计算svg元素的宽高,实现自适应尺寸
const clientHeight = circleProgress.value.clientHeight
const clientWidth = circleProgress.value.clientWidth
if(clientWidth > clientHeight){
width.value = clientHeight
}else{
width.value = clientWidth
}
updateProgress(props.percent)
})
watch(() => props.percent, (newValue) => {
updateProgress(newValue)
})
function updateProgress(percent) {
setTimeout(() => {
const radius = circle.value.r.baseVal.value;
const circumference = radius * 2 * Math.PI;
// 设置进度圆环
strokeDasharray.value = circumference;
const offset = circumference - percent / 100 * circumference;
strokeDashoffset.value = offset;
// 更新文字
text.value.textContent = `${percent}%`;
},20)
}
</script>
<style lang="scss" scoped>
.circle-progress {
width: 100%;
height: 100%;
.progressBar {
width: 100%;
height: 100%;
}
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111