P粉7397060892023-08-16 21:44:17
我為標籤新增了一個獨立的容器,並將其樣式設定為與圖表顏色相符。我使用flexbox將標籤定位在圖表的左側。 positionLabelsContainer()函數根據圖表大小定位標籤容器,並新增了事件監聽器以在視窗調整大小時重新定位。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>饼图示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <div style="position: relative;"> <canvas id="pieChart" width="400" height="400"></canvas> <div id="labels-container" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center;"> <div style="display: flex; flex-direction: column; align-items: flex-start;"> <div style="background-color: rgba(71, 190, 125, 1); width: 10px; height: 10px; margin-bottom: 5px;"></div> <div style="background-color: rgba(241, 65, 108, 1); width: 10px; height: 10px;"></div> </div> <div style="display: flex; flex-direction: column; align-items: flex-start; margin-left: 5px;"> <div>在线: 8%</div> <div>离线: 2%</div> </div> </div> </div> <script> // 获取canvas元素 var canvas = document.getElementById('pieChart'); var labelsContainer = document.getElementById('labels-container'); // 创建饼图 var pieChart = new Chart(canvas, { type: 'pie', data: { labels: ['在线', '离线'], datasets: [{ data: [8, 2], backgroundColor: ['rgba(71, 190, 125, 1)', 'rgba(241, 65, 108, 1)'], borderWidth: 0 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false }, datalabels: false // 禁用数据标签,因为它们显示在自定义容器中 } } }); // 根据图表大小定位标签容器 function positionLabelsContainer() { labelsContainer.style.width = canvas.offsetWidth + 'px'; labelsContainer.style.height = canvas.offsetHeight + 'px'; } positionLabelsContainer(); // 初始定位 window.addEventListener('resize', positionLabelsContainer); // 调整大小时更新 </script> </body> </html>