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 centerX = 100;
const centerY = 100;
const radius = 80;
const startAngle = 0;
const endAngle = Math.PI * 1.5; // 270度
const start = this.polarToCartesian(centerX, centerY, radius, endAngle);
const end = this.polarToCartesian(centerX, centerY, radius, startAngle);
const largeArcFlag = endAngle - startAngle <= Math.PI ? "0" : "1";
return `M ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArcFlag} 0 ${end.x} ${end.y}`;
}
},
methods: {
polarToCartesian(centerX, centerY, radius, angleInRadians) {
return {
x: centerX + radius * Math.cos(angleInRadians),
y: centerY + radius * Math.sin(angleInRadians)
};
}
}
};
</script>
使用 Canvas 绘制动态圆弧
通过 Vue 的 ref 和生命周期钩子访问 Canvas 上下文,实现动态圆弧绘制和着色。

<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");
const centerX = 100;
const centerY = 100;
const radius = 80;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, Math.PI * 1.5, false);
ctx.strokeStyle = "#FF5722";
ctx.lineWidth = 10;
ctx.stroke();
// 填充扇形(可选)
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, 0, Math.PI * 0.5, false);
ctx.fillStyle = "rgba(33, 150, 243, 0.5)";
ctx.fill();
}
}
};
</script>
使用第三方库(如 D3.js)
对于复杂圆弧需求(如仪表盘),D3.js 提供更高级的弧形生成器。
<template>
<svg ref="svg" width="200" height="200"></svg>
</template>
<script>
import * as d3 from "d3";
export default {
mounted() {
this.renderArc();
},
methods: {
renderArc() {
const svg = d3.select(this.$refs.svg);
const arcGenerator = d3.arc()
.innerRadius(50)
.outerRadius(80)
.startAngle(0)
.endAngle(Math.PI * 1.2);
svg.append("path")
.attr("d", arcGenerator())
.attr("fill", "#9C27B0")
.attr("stroke", "#673AB7")
.attr("stroke-width", 2);
}
}
};
</script>
关键参数说明
-
SVG 路径命令:
A rx ry x-axis-rotation large-arc-flag sweep-flag x y
large-arc-flag:1 表示大于 180 度的弧,0 表示小弧sweep-flag:1 表示顺时针方向,0 表示逆时针
-
Canvas 的
arc()方法:arc(x, y, radius, startAngle, endAngle, anticlockwise)- 角度单位为弧度(0 到 2π)
anticlockwise为true时逆时针绘制
-
动态响应:在 Vue 中可将圆弧参数设为
data或props,通过watch触发重绘。






