vue实现扇形图
Vue 实现扇形图的方法
使用 ECharts 实现
安装 ECharts 依赖:
npm install echarts --save
在 Vue 组件中引入并使用:
<template>
<div ref="chart" style="width: 400px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
const myChart = echarts.init(chartDom);
const option = {
series: [{
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
]
}]
};
myChart.setOption(option);
}
}
};
</script>
使用 D3.js 实现
安装 D3.js 依赖:
npm install d3 --save
Vue 组件实现:
<template>
<svg ref="svg" width="400" height="400"></svg>
</template>
<script>
import * as d3 from 'd3';
export default {
mounted() {
this.drawChart();
},
methods: {
drawChart() {
const data = [10, 20, 30, 40, 50];
const svg = d3.select(this.$refs.svg);
const width = +svg.attr('width');
const height = +svg.attr('height');
const radius = Math.min(width, height) / 2;
const g = svg.append('g')
.attr('transform', `translate(${width / 2}, ${height / 2})`);
const color = d3.scaleOrdinal(['#98abc5', '#8a89a6', '#7b6888', '#6b486b', '#a05d56']);
const pie = d3.pie();
const arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);
const arcs = g.selectAll('.arc')
.data(pie(data))
.enter()
.append('g')
.attr('class', 'arc');
arcs.append('path')
.attr('d', arc)
.attr('fill', (d, i) => color(i));
}
}
};
</script>
使用 Canvas API 手动绘制
Vue 组件实现:
<template>
<canvas ref="canvas" width="400" height="400"></canvas>
</template>
<script>
export default {
mounted() {
this.drawSector();
},
methods: {
drawSector() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 150;
const data = [
{ value: 30, color: '#FF6384' },
{ value: 50, color: '#36A2EB' },
{ value: 100, color: '#FFCE56' },
{ value: 40, color: '#4BC0C0' }
];
let total = data.reduce((sum, item) => sum + item.value, 0);
let startAngle = 0;
data.forEach(item => {
const sliceAngle = (item.value / total) * 2 * Math.PI;
ctx.beginPath();
ctx.fillStyle = item.color;
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, startAngle + sliceAngle);
ctx.closePath();
ctx.fill();
startAngle += sliceAngle;
});
}
}
};
</script>
注意事项
- ECharts 方案适合需要丰富交互和动画效果的场景
- D3.js 方案提供更底层的控制,适合自定义需求
- Canvas API 方案最轻量,但需要手动处理所有绘制逻辑
- 响应式设计需要考虑在窗口大小变化时重新绘制图表
- 大数据量场景下需要注意性能优化







