vue实现扇形图
使用 SVG 绘制扇形图
在 Vue 中可以通过 SVG 的 <path> 元素绘制扇形。计算扇形的路径需要用到极坐标公式,结合 d 属性生成路径数据。
计算公式:
- 扇形路径由圆心、半径、起始角度和结束角度决定。
- 路径命令
M(移动到起点)、A(画弧)、L(画线到圆心)、Z(闭合路径)。
示例代码:
<template>
<svg width="200" height="200" viewBox="0 0 200 200">
<path :d="getSectorPath(100, 100, 80, 0, 90)" fill="#42b983" />
<path :d="getSectorPath(100, 100, 80, 90, 180)" fill="#ff7e67" />
</svg>
</template>
<script>
export default {
methods: {
getSectorPath(cx, cy, r, startAngle, endAngle) {
const startRad = (startAngle * Math.PI) / 180;
const endRad = (endAngle * 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>
使用 ECharts 实现扇形图
ECharts 提供更丰富的图表配置,适合复杂需求。通过 Vue-ECharts 库可以快速集成。
安装依赖:
npm install echarts vue-echarts
示例代码:
<template>
<v-chart :option="chartOption" style="height: 400px" />
</template>
<script>
import { use } from "echarts/core";
import { PieChart } from "echarts/charts";
import { TitleComponent, TooltipComponent } from "echarts/components";
import VChart from "vue-echarts";
use([PieChart, TitleComponent, TooltipComponent]);
export default {
components: { VChart },
data() {
return {
chartOption: {
title: { text: "扇形图示例" },
series: [
{
type: "pie",
radius: ["50%", "70%"],
data: [
{ value: 40, name: "A" },
{ value: 30, name: "B" },
{ value: 20, name: "C" },
],
},
],
},
};
},
};
</script>
使用 D3.js 动态生成扇形图
D3.js 适合需要高度自定义的场景,结合 Vue 实现动态数据绑定。
示例代码:

<template>
<svg ref="chart" width="200" height="200"></svg>
</template>
<script>
import * as d3 from "d3";
export default {
mounted() {
this.drawChart();
},
methods: {
drawChart() {
const data = [30, 70];
const svg = d3.select(this.$refs.chart);
const pie = d3.pie()(data);
const arc = d3
.arc()
.innerRadius(0)
.outerRadius(80);
svg
.selectAll("path")
.data(pie)
.enter()
.append("path")
.attr("d", arc)
.attr("fill", (d, i) => (i === 0 ? "#42b983" : "#ff7e67"))
.attr("transform", "translate(100, 100)");
},
},
};
</script>
注意事项
- 性能优化:大数据量时考虑使用 Canvas(如 ECharts)替代 SVG。
- 响应式设计:通过监听窗口大小变化动态调整图表尺寸。
- 动画效果:ECharts 或 D3.js 支持过渡动画,增强用户体验。






