Chart.js 是一个流行的 JavaScript 图表库,支持折线图(Line Chart)。以下是一个基本的折线图示例:

1. 安装 Chart.js

如果你使用 npm:

npm install chart.js

或者通过 CDN 引入:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


2. HTML 代码

在 HTML 文件中添加一个 <canvas> 画布:

<canvas id="myLineChart"></canvas>


3. JavaScript 代码

<script>
const ctx = document.getElementById('myLineChart').getContext('2d');

const myChart = new Chart(ctx, {
    type: 'line', // 折线图
    data: {
        labels: ['1月', '2月', '3月', '4月', '5月', '6月'], // X 轴数据
        datasets: [{
            label: '销售额(万元)',
            data: [10, 25, 40, 30, 50, 60], // Y 轴数据
            borderColor: 'rgba(75, 192, 192, 1)', // 线条颜色
            backgroundColor: 'rgba(75, 192, 192, 0.2)', // 填充色
            borderWidth: 2, // 线条宽度
            tension: 0.4 // 线条弯曲度(0 = 直线)
        }]
    },
    options: {
        responsive: true, // 适应屏幕大小
        plugins: {
            legend: { display: true } // 显示图例
        },
        scales: {
            x: { 
                title: { display: true, text: '月份' } 
            },
            y: { 
                title: { display: true, text: '销售额' },
                beginAtZero: true
            }
        }
    }
});
</script>


4. 可选增强

添加多个数据集

可以在 datasets 数组中添加多个对象:

datasets: [
    {
        label: '产品 A',
        data: [10, 20, 30, 40, 50, 60],
        borderColor: 'rgba(255, 99, 132, 1)',
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderWidth: 2
    },
    {
        label: '产品 B',
        data: [15, 25, 35, 45, 55, 65],
        borderColor: 'rgba(54, 162, 235, 1)',
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderWidth: 2
    }
]

显示数据点

pointRadius: 5, // 数据点大小
pointHoverRadius: 7 // 悬停时数据点大小

添加动画

animation: {
    duration: 1000, // 动画持续时间
    easing: 'easeInOutQuart' // 缓动函数
}


这样,你就可以在网页上创建一个美观的折线图了!🚀