vue实现画圆弧并着色
在 Vue 中实现画圆弧并着色
使用 Canvas API 绘制圆弧
在 Vue 组件的 mounted 钩子中,通过 Canvas API 绘制圆弧。创建一个 canvas 元素并获取其上下文:
<template>
<canvas ref="arcCanvas" width="200" height="200"></canvas>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.arcCanvas;
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 1.5); // 圆心 (100,100), 半径 80, 0 到 270°
ctx.strokeStyle = '#3498db';
ctx.lineWidth = 10;
ctx.stroke();
}
};
</script>
填充圆弧颜色
使用 fillStyle 和 fill 方法填充圆弧区域。注意需调用 closePath 闭合路径:
ctx.beginPath();
ctx.arc(100, 100, 80, 0, Math.PI * 1.5);
ctx.closePath(); // 闭合路径
ctx.fillStyle = 'rgba(52, 152, 219, 0.5)';
ctx.fill();
动态绑定圆弧参数
通过 Vue 的响应式数据动态控制圆弧属性:
<template>
<canvas ref="arcCanvas" width="200" height="200"></canvas>
<input v-model="endAngle" type="range" min="0" max="6.28" step="0.01">
</template>
<script>
export default {
data() {
return {
endAngle: 1.5 * Math.PI
};
},
watch: {
endAngle() {
this.drawArc();
}
},
mounted() {
this.drawArc();
},
methods: {
drawArc() {
const canvas = this.$refs.arcCanvas;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(100, 100, 80, 0, parseFloat(this.endAngle));
ctx.strokeStyle = '#e74c3c';
ctx.lineWidth = 10;
ctx.stroke();
}
}
};
</script>
使用 SVG 实现圆弧
作为替代方案,可以使用 SVG 的 <path> 或 <circle> 元素:
<template>
<svg width="200" height="200">
<path
d="M100,20 A80,80 0 0 1 180,100"
stroke="#2ecc71"
stroke-width="10"
fill="none"
/>
</svg>
</template>
添加动画效果
通过 CSS 或 JavaScript 实现圆弧动画。例如使用 requestAnimationFrame:
methods: {
animateArc() {
let progress = 0;
const animate = () => {
progress += 0.01;
this.endAngle = progress * Math.PI * 2;
if (progress < 1) requestAnimationFrame(animate);
};
animate();
}
}
以上方法提供了从基础绘制到动态交互的完整实现路径,可根据具体需求选择适合的技术方案。







