前端html 饼图
时间: 2023-06-28 16:05:27 浏览: 62
要制作一个前端 HTML 饼图,你可以使用 HTML5 的 canvas 元素和 JavaScript 来实现。下面是一个简单的例子:
HTML 代码:
```html
<canvas id="pie-chart" width="400" height="400"></canvas>
```
JavaScript 代码:
```javascript
const canvas = document.getElementById('pie-chart');
const ctx = canvas.getContext('2d');
// 绘制饼图
function drawPieChart(data) {
const total = data.reduce((acc, val) => acc + val.value, 0);
let startAngle = -Math.PI / 2;
data.forEach(slice => {
const sliceAngle = (slice.value / total) * 2 * Math.PI;
ctx.fillStyle = slice.color;
ctx.beginPath();
ctx.moveTo(canvas.width / 2, canvas.height / 2);
ctx.arc(canvas.width / 2, canvas.height / 2, canvas.height / 2, startAngle, startAngle + sliceAngle);
ctx.closePath();
ctx.fill();
startAngle += sliceAngle;
});
}
// 示例数据
const data = [
{ label: 'Apple', value: 30, color: '#ff6384' },
{ label: 'Banana', value: 20, color: '#36a2eb' },
{ label: 'Orange', value: 15, color: '#ffce56' },
{ label: 'Grape', value: 10, color: '#4bc0c0' },
{ label: 'Mango', value: 25, color: '#9966ff' }
];
drawPieChart(data);
```
上面的代码会在 canvas 元素中绘制一个饼图,数据和颜色可以根据需要自定义。你也可以添加一些动态效果来使饼图更加生动。