Chart.js 图表示例

使用 Chart.js 创建各种类型的交互式图表

动态控制

0
总销售额
0
平均销售额
0
最高销售额

柱状图

折线图

饼图

环形图

雷达图

极坐标图

核心代码

// 创建柱状图
const barChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['一月', '二月', '三月', '四月', '五月', '六月'],
        datasets: [{
            label: '销售额',
            data: [65, 59, 80, 81, 56, 55],
            backgroundColor: 'rgba(102, 126, 234, 0.6)',
            borderColor: 'rgba(102, 126, 234, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: true,
                position: 'top'
            }
        }
    }
});

// 动态添加数据
function addRandomData() {
    const months = ['七月', '八月', '九月', '十月', '十一月', '十二月'];
    const index = barChart.data.labels.length % months.length;
    const label = months[index] || `月${barChart.data.labels.length + 1}`;
    const value = Math.floor(Math.random() * 100);

    barChart.data.labels.push(label);
    barChart.data.datasets.forEach(dataset => {
        dataset.data.push(value);
    });
    barChart.update();
    updateStats();
}