vue实现圆环进度
Vue 实现圆环进度的方法
使用 SVG 实现圆环进度
SVG 的 circle 和 stroke-dasharray 属性可以轻松实现圆环进度效果。以下是一个示例代码:
<template>
<div class="circle-progress">
<svg width="100" height="100" viewBox="0 0 100 100">
<circle
cx="50"
cy="50"
r="45"
fill="none"
stroke="#e6e6e6"
stroke-width="10"
/>
<circle
cx="50"
cy="50"
r="45"
fill="none"
stroke="#42b983"
stroke-width="10"
stroke-dasharray="283"
:stroke-dashoffset="283 - (283 * progress) / 100"
/>
</svg>
<div class="progress-text">{{ progress }}%</div>
</div>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
},
},
};
</script>
<style>
.circle-progress {
position: relative;
width: 100px;
height: 100px;
}
.progress-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 16px;
font-weight: bold;
}
</style>
使用 Canvas 实现圆环进度
Canvas 提供了更灵活的绘图方式,适合需要动态效果的场景:
<template>
<div class="circle-progress">
<canvas ref="canvas" width="100" height="100"></canvas>
<div class="progress-text">{{ progress }}%</div>
</div>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
},
},
mounted() {
this.drawProgress();
},
watch: {
progress() {
this.drawProgress();
},
},
methods: {
drawProgress() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext("2d");
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 45;
const lineWidth = 10;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制背景圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
ctx.strokeStyle = "#e6e6e6";
ctx.lineWidth = lineWidth;
ctx.stroke();
// 绘制进度圆环
ctx.beginPath();
ctx.arc(
centerX,
centerY,
radius,
-Math.PI / 2,
-Math.PI / 2 + (Math.PI * 2 * this.progress) / 100
);
ctx.strokeStyle = "#42b983";
ctx.lineWidth = lineWidth;
ctx.stroke();
},
},
};
</script>
使用第三方库
如果需要更复杂的效果,可以考虑使用第三方库,如 vue-css-donut-chart:
npm install vue-css-donut-chart
使用示例:
<template>
<donut-chart
:size="100"
:thickness="10"
:text="progress + '%'"
:sections="[{ value: progress, color: '#42b983' }]"
/>
</template>
<script>
import DonutChart from "vue-css-donut-chart";
export default {
components: { DonutChart },
props: {
progress: {
type: Number,
default: 0,
},
},
};
</script>
注意事项
- SVG 方法简单且性能较好,适合静态或简单动画场景。
- Canvas 方法适合需要复杂交互或动画的场景,但需要注意性能优化。
- 第三方库可以快速实现复杂效果,但会增加项目体积。






