在React JS中创建环形图:实现方法及优质库推荐
创建自定义环形图的实现方案与推荐库
一、推荐的优质图表库
以下几个都是行业内广泛使用的成熟工具,能适配不同层级的需求:
- Chart.js:轻量易上手,API简洁,支持基础环形图(Doughnut Chart)快速搭建,适合需求不复杂的场景。
- ECharts:功能全面,自定义程度极高,内置丰富配置项,能轻松实现带中心文本、交互效果、复杂样式的环形图。
- D3.js:完全自由定制的可视化工具,适合需要1:1复刻目标图细节的进阶需求,不过学习曲线相对陡峭。
二、具体实现示例
1. Chart.js 快速实现基础环形图
通过简单配置就能生成环形图,还能灵活调整环形粗细、颜色、图例等:
<canvas id="doughnutChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('doughnutChart').getContext('2d'); new Chart(ctx, { type: 'doughnut', data: { labels: ['已完成', '待进行', '延期'], datasets: [{ data: [45, 35, 20], backgroundColor: ['#28a745', '#17a2b8', '#dc3545'], borderWidth: 0, cutout: '70%' // 控制环形空心大小,数值越大环越细 }] }, options: { plugins: { title: { display: true, text: '任务进度', font: { size: 18 } }, legend: { position: 'bottom' } } } }); </script>
2. ECharts 实现带中心文本的定制化环形图
如果你的目标图需要中心显示汇总信息,ECharts的配置非常便捷:
<div id="echartsRing" style="width:400px;height:400px;"></div> <script> const myChart = echarts.init(document.getElementById('echartsRing')); const option = { series: [{ type: 'pie', radius: ['50%', '75%'], center: ['50%', '50%'], data: [ { value: 25, name: '一季度' }, { value: 30, name: '二季度' }, { value: 20, name: '三季度' }, { value: 25, name: '四季度' } ], label: { show: true, position: 'center', formatter: '年度完成率\n{total}%', fontSize: 16, fontWeight: 'bold', color: '#333' }, labelLine: { show: false } }] }; // 计算总完成率 option.series[0].label.formatter = `年度完成率\n${option.series[0].data.reduce((sum, item) => sum + item.value, 0)}%`; myChart.setOption(option); </script>
3. D3.js 高度自定义环形图(适配复杂需求)
如果需要完全复刻你提供的环形图细节,D3.js可以实现像素级的定制:
const width = 400; const height = 400; const radius = Math.min(width, height) / 2; // 创建SVG容器 const svg = d3.select('body') .append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', `translate(${width/2}, ${height/2})`); // 模拟数据 const data = [30, 15, 55]; // 颜色映射 const colors = ['#ff9f40', '#ff6b6b', '#4ecdc4']; // 创建弧形生成器 const arc = d3.arc() .innerRadius(radius * 0.6) .outerRadius(radius); // 创建饼图布局 const pie = d3.pie().value(d => d); // 绘制环形分段 svg.selectAll('path') .data(pie(data)) .enter() .append('path') .attr('d', arc) .attr('fill', (d, i) => colors[i]) .attr('stroke', '#fff') .attr('stroke-width', 2) // 添加hover效果 .on('mouseover', function() { d3.select(this).attr('opacity', 0.8); }) .on('mouseout', function() { d3.select(this).attr('opacity', 1); }); // 添加中心文本 svg.append('text') .attr('text-anchor', 'middle') .attr('dy', '-0.5em') .style('font-size', '24px') .style('font-weight', 'bold') .text('总进度'); svg.append('text') .attr('text-anchor', 'middle') .attr('dy', '1em') .style('font-size', '18px') .text(`${data.reduce((a,b)=>a+b, 0)}%`);
根据你提供的环形图样式,可以基于上述示例进一步调整颜色、分段宽度、交互效果、文本样式等,完全匹配需求。
内容的提问来源于stack exchange,提问作者Mandar Deshpande
相关产品推荐
相关产品推荐

