vue实现画圆弧并着色
使用 SVG 绘制圆弧并着色
在 Vue 中可以通过 SVG 的 <path> 或 <circle> 元素绘制圆弧。SVG 的路径命令(如 A)可以精确控制圆弧的半径、起始角度和结束角度。
<template>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
:d="arcPath"
fill="none"
stroke="#4CAF50"
stroke-width="10"
/>
</svg>
</template>
<script>
export default {
computed: {
arcPath() {
const radius = 80;
const startAngle = 0;
const endAngle = Math.PI * 1.5; // 270度
const startX = 100 + radius * Math.cos(startAngle);
const startY = 100 + radius * Math.sin(startAngle);
const endX = 100 + radius * Math.cos(endAngle);
const endY = 100 + radius * Math.sin(endAngle);
const largeArcFlag = endAngle - startAngle <= Math.PI ? 0 : 1;
return `M ${startX} ${startY} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${endX} ${endY}`;
}
}
};
</script>
使用 Canvas 绘制圆弧
通过 Canvas 的 arc() 方法可以动态绘制圆弧,结合 Vue 的 ref 和生命周期钩子实现。
<template>
<canvas ref="canvas" width="200" height="200"></canvas>
</template>
<script>
export default {
mounted() {
this.drawArc();
},
methods: {
drawArc() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 1.5); // 圆心(100,100),半径80,0到270度
ctx.strokeStyle = '#FF5722';
ctx.lineWidth = 10;
ctx.stroke();
}
}
};
</script>
渐变色圆弧
在 Canvas 中可以使用 createLinearGradient 或 createRadialGradient 实现渐变色效果。
drawGradientArc() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, 200, 200);
gradient.addColorStop(0, '#FF9800');
gradient.addColorStop(1, '#E91E63');
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 1.5);
ctx.strokeStyle = gradient;
ctx.lineWidth = 10;
ctx.stroke();
}
动态圆弧动画
通过 Vue 的响应式数据和 requestAnimationFrame 实现动画效果。
<template>
<canvas ref="canvas" width="200" height="200"></canvas>
</template>
<script>
export default {
data() {
return {
progress: 0,
animationId: null
};
},
mounted() {
this.animateArc();
},
beforeUnmount() {
cancelAnimationFrame(this.animationId);
},
methods: {
animateArc() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const drawFrame = () => {
ctx.clearRect(0, 0, 200, 200);
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 2 * this.progress);
ctx.strokeStyle = '#3F51B5';
ctx.lineWidth = 10;
ctx.stroke();
this.progress += 0.01;
if (this.progress > 1) this.progress = 0;
this.animationId = requestAnimationFrame(drawFrame);
};
drawFrame();
}
}
};
</script>
第三方库支持
使用 vue-arc-progress 等现成库快速实现圆弧进度条。
npm install vue-arc-progress
<template>
<arc-progress
:progress="75"
:thickness="8"
:size="200"
fill-color="#009688"
/>
</template>
<script>
import ArcProgress from 'vue-arc-progress';
export default {
components: { ArcProgress }
};
</script>






