vue实现扇形进度
Vue 实现扇形进度条
实现扇形进度条可以通过 SVG 或 Canvas 绘制,以下是两种常见方法:
使用 SVG 绘制扇形进度条
SVG 的 path 元素结合 d 属性可以绘制扇形。计算扇形的路径需要使用三角函数。

<template>
<div class="progress-container">
<svg width="200" height="200" viewBox="0 0 200 200">
<path
:d="getSectorPath(100, 100, 80, 0, progressAngle)"
fill="#4CAF50"
/>
</svg>
</div>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
validator: value => value >= 0 && value <= 100
}
},
computed: {
progressAngle() {
return (this.progress / 100) * 360;
}
},
methods: {
getSectorPath(cx, cy, r, startAngle, endAngle) {
const startRad = (startAngle - 90) * Math.PI / 180;
const endRad = (endAngle - 90) * Math.PI / 180;
const x1 = cx + r * Math.cos(startRad);
const y1 = cy + r * Math.sin(startRad);
const x2 = cx + r * Math.cos(endRad);
const y2 = cy + r * Math.sin(endRad);
const largeArcFlag = endAngle - startAngle <= 180 ? 0 : 1;
return `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArcFlag} 1 ${x2} ${y2} Z`;
}
}
};
</script>
使用 Canvas 绘制扇形进度条
Canvas 的 arc 方法可以直接绘制扇形。

<template>
<div class="progress-container">
<canvas ref="canvas" width="200" height="200"></canvas>
</div>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 0,
validator: value => value >= 0 && value <= 100
}
},
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 = 80;
const startAngle = -0.5 * Math.PI;
const endAngle = startAngle + (this.progress / 100) * 2 * Math.PI;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = '#4CAF50';
ctx.fill();
}
}
};
</script>
添加动画效果
为进度条添加平滑过渡动画,可以使用 CSS 或 JavaScript 动画。
// 在 watch 中添加动画
watch: {
progress(newVal, oldVal) {
let current = oldVal;
const animate = () => {
if (Math.abs(current - newVal) < 0.5) {
current = newVal;
this.drawProgress();
return;
}
current += (newVal - oldVal) / 30;
this.drawProgress();
requestAnimationFrame(animate);
};
animate();
}
}
使用第三方库
如果需要更复杂的效果,可以考虑使用第三方库如:
vue-awesome-progressprogressbar.jsChart.js的饼图
这些库提供了更多自定义选项和动画效果。






