好的,以下是一个随数据变化的饼图示例:
HTML 代码:
```html
```
CSS 代码:
```css
.pie-chart {
position: relative;
width: 300px;
height: 300px;
}
#chart {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
```
JS 代码:
```javascript
let data = [
{ label: 'A', value: 30, color: '#f44336' },
{ label: 'B', value: 20, color: '#9c27b0' },
{ label: 'C', value: 50, color: '#2196f3' }
];
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
function drawChart() {
// 计算总值
const totalValue = data.reduce((sum, item) => sum + item.value, 0);
// 绘制饼图
let startAngle = 0;
data.forEach(item => {
const angle = (item.value / totalValue) * Math.PI * 2;
ctx.beginPath();
ctx.moveTo(canvas.width / 2, canvas.height / 2);
ctx.arc(canvas.width / 2, canvas.height / 2, canvas.width / 2, startAngle, startAngle + angle);
ctx.fillStyle = item.color;
ctx.fill();
startAngle += angle;
});
// 绘制图例
let legendHTML = '';
data.forEach(item => {
legendHTML += `
${item.label}: ${item.value}
`;
});
document.querySelector('.pie-chart').insertAdjacentHTML('beforeend', `
${legendHTML}
`);
}
function updateChart(newData) {
data = newData;
ctx.clearRect(0, 0, canvas.width, canvas.height);
document.querySelector('.legend').remove();
drawChart();
}
drawChart();
// 模拟数据变化
setInterval(() => {
const newData = [
{ label: 'A', value: Math.floor(Math.random