| 庫 | 語法風格 | 扇形圖交互 | 體積(gz) | 生態/授權 | 推薦指數 |
|---|---|---|---|---|---|
| ECharts 5 | 聲明式 Option JSON | 豐富:點擊/懸停/選中/拖拽/下鉆/動畫回調 | ~150KB (按需引入 ~50KB) | Apache 2.0,百度維護,中文文檔最全,社區最活躍 | ⭐⭐⭐⭐⭐ |
| Chart.js 4 | 配置對象 + 類實例 | 基礎:點擊/懸停/動畫,插件擴展較弱 | ~60KB | MIT,簡單易上手,適合輕量項目 | ⭐⭐⭐⭐ |
| HighCharts | 聲明式 Options | 極豐富,商業級交互細節 | ~200KB | 商業授權(免費僅非商業),文檔優秀 | ⭐⭐⭐ (商業項目) |
| AntV G2Plot | Grammar of Graphics | 優秀,語義化交互 | ~120KB | MIT,螞蟻金服出品,TypeScript 優先 | ⭐⭐⭐⭐ (React/Vue/TS項目) |
| D3.js | 底層 SVG 操作 | 完全可控,但需手寫大量代碼 | ~90KB (核心) | BSD-3,學習曲線極陡 | ⭐⭐ (高度定制) |
<div id="pie-chart" style="width: 600px; height: 400px;"></div>
<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
<script>
const chart = echarts.init(document.getElementById('pie-chart'));
// 1. 基礎配置
const option = {
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
legend: { orient: 'vertical', left: 'left' },
series: [{
name: '訪問來源',
type: 'pie',
radius: ['40%', '70%'], // 環形圖
avoidLabelOverlap: false,
itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
label: { show: false, position: 'center' },
emphasis: { label: { show: true, fontSize: 18, fontWeight: 'bold' } },
labelLine: { show: false },
data: [] // 動態填充
}]
};
chart.setOption(option);
// 2. 動態載入數據並更新
fetch('/api/stats/source')
.then(r => r.json())
.then(data => {
chart.setOption({
series: [{ data: data.map(d => ({ value: d.count, name: d.source })) }]
});
});
// 3. 核心交互:點擊扇區跳轉/彈窗
chart.on('click', params => {
if (params.componentType === 'series') {
console.log('點擊扇區:', params.name, params.value, params.percent);
// window.open(`/detail?source=${encodeURIComponent(params.name)}`);
// 或彈窗: showModal(params.name, params.value);
}
});
// 4. 懸停高亮聯動外部列表
chart.on('mouseover', params => {
if (params.componentType === 'series') {
highlightExternalItem(params.name);
}
});
chart.on('mouseout', () => clearExternalHighlight());
// 5. 響應式 resize
window.addEventListener('resize', () => chart.resize());
</script>
tooltip: { formatter: (p) => `${p.name}
${p.value} 次` }。animationDurationUpdate: 500, animationEasing: 'cubicOut'。動態生成可交互扇形圖,**ECharts 5 以聲明式 Option、豐富事件系統、按需打包、中文生態優勢成為首選**。核心步驟:init → setOption(data) → on('click', handler) → resize()。避免手寫 SVG/D3,除非有極度非標準定制需求。