<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>環餅圖顯示總數</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<style>
#main { width: 600px; height: 400px; margin: 0 auto; }
</style>
</head>
<body>
<div id="main"></div>
<script type="text/javascript">
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
const data = [
{value: 335, name: '直接訪問'},
{value: 310, name: '郵件營銷'},
{value: 234, name: '聯盟廣告'},
{value: 0, name: '視頻廣告'},
{value: 0, name: '搜索引擎'}
];
const total = data.reduce((sum, item) => sum + item.value, 0);
var option = {
tooltip: {
trigger: 'item',
? // 關鍵修復:1.確保0值也顯示提示
formatter: function(params) {
return `${params.name}: ${params.value}`;
}
},
legend: {
top: '5%',
left: 'center'
},
series: [{
name: '訪問量統計',
type: 'pie',
radius: ['40%', '70%'],
//關鍵修復:2.確保0值也顯示提示,強制顯示0值項
stillShowZeroSum: true,
?//關鍵修復:3.確保0值也顯示提示 設置最小角度使0值可見
minAngle: 1, ?// 最小角度5度(可調整)
avoidLabelOverlap: false,
// 關鍵修改:禁用普通狀態下的標簽顯示
label: {
show: false, // 關閉每個扇形的標簽
position: 'center'
},
? // 關鍵修改:只在高亮狀態顯示中心標簽
emphasis: {
disabled: false, // 確保高亮效果可用
scale: true, ? ? // 啟用放大效果
scaleSize: 5, ? ?// 放大尺寸
label: {
show: false,
position: 'center',
formatter: `總訪問量\n{total|${total}}`, ?// 只顯示總數
fontSize: 18,
fontWeight: 'normal',
rich: {
total: {
fontSize: 28,
fontWeight: 'bold',
color: '#333',
lineHeight: 40
}
}
}
},
labelLine: {
show: false
},
data: data
}]
};
? ? ? ? myChart.setOption(option);
// 添加自定義中心標簽(非交互狀態時顯示)
const centerText = document.createElement('div');
centerText.style.position = 'absolute';
centerText.style.textAlign = 'center';
centerText.style.pointerEvents = 'none';
centerText.innerHTML = `
<div style="font-size: 18px; color: #666;">總訪問量</div>
<div style="font-size: 28px; font-weight: bold; color: #333;">${total}</div>
`;
? // 將中心標簽定位到圖表中心
chartDom.appendChild(centerText);
// 監聽圖表尺寸變化,保持居中
const resizeObserver = new ResizeObserver(() => {
const { width, height } = chartDom.getBoundingClientRect();
centerText.style.width = width + 'px';
centerText.style.top = (height / 2 - 30) + 'px';
});
resizeObserver.observe(chartDom);
</script>
</body>
</html>