vue实现圆环
Vue 实现圆环的方法
在 Vue 中实现圆环可以通过多种方式完成,以下是几种常见的方法:
使用 SVG 绘制圆环
SVG 是一种矢量图形格式,适合绘制圆环。可以通过 circle 和 path 元素实现圆环效果。

<template>
<svg width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="none" stroke="#ccc" stroke-width="10" />
<circle
cx="50"
cy="50"
r="40"
fill="none"
stroke="#4CAF50"
stroke-width="10"
stroke-dasharray="251.2"
:stroke-dashoffset="dashOffset"
/>
</svg>
</template>
<script>
export default {
data() {
return {
progress: 60, // 进度百分比
};
},
computed: {
dashOffset() {
const circumference = 2 * Math.PI * 40;
return circumference * (1 - this.progress / 100);
},
},
};
</script>
使用 CSS 实现圆环
通过 CSS 的 border-radius 和 border 属性可以实现圆环效果。

<template>
<div class="ring-container">
<div class="ring-background"></div>
<div class="ring-progress" :style="progressStyle"></div>
</div>
</template>
<script>
export default {
data() {
return {
progress: 60, // 进度百分比
};
},
computed: {
progressStyle() {
return {
transform: `rotate(${360 * this.progress / 100}deg)`,
};
},
},
};
</script>
<style>
.ring-container {
position: relative;
width: 100px;
height: 100px;
}
.ring-background {
position: absolute;
width: 100%;
height: 100%;
border: 10px solid #ccc;
border-radius: 50%;
}
.ring-progress {
position: absolute;
width: 100%;
height: 100%;
border: 10px solid #4CAF50;
border-radius: 50%;
clip: rect(0, 50px, 100px, 0);
}
</style>
使用 Canvas 绘制圆环
Canvas 提供更灵活的绘图能力,适合动态圆环效果。
<template>
<canvas ref="canvas" width="100" height="100"></canvas>
</template>
<script>
export default {
data() {
return {
progress: 60, // 进度百分比
};
},
mounted() {
this.drawRing();
},
methods: {
drawRing() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 40;
const lineWidth = 10;
// 绘制背景圆环
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.strokeStyle = '#ccc';
ctx.lineWidth = lineWidth;
ctx.stroke();
// 绘制进度圆环
ctx.beginPath();
ctx.arc(
centerX,
centerY,
radius,
-Math.PI / 2,
(2 * Math.PI * this.progress / 100) - Math.PI / 2
);
ctx.strokeStyle = '#4CAF50';
ctx.lineWidth = lineWidth;
ctx.stroke();
},
},
watch: {
progress() {
this.drawRing();
},
},
};
</script>
使用第三方库
如果需要更复杂的功能,可以使用第三方库如 vue-awesome-progress 或 chart.js。
<template>
<vue-awesome-progress
type="circle"
:progress="progress"
:size="100"
:stroke-width="10"
:stroke-color="'#4CAF50'"
:stroke-background="'#ccc'"
/>
</template>
<script>
import VueAwesomeProgress from 'vue-awesome-progress';
export default {
components: {
VueAwesomeProgress,
},
data() {
return {
progress: 60,
};
},
};
</script>
总结
- SVG:适合静态或简单动态圆环,代码简洁。
- CSS:适合纯样式圆环,性能较好。
- Canvas:适合复杂动态效果,灵活性高。
- 第三方库:快速实现功能,适合复杂需求。






