教程 chartjs tutorial

折线图 Line

折线图用于展示数据随时间或类别的变化趋势。使用 Chart.js 可以轻松绘制丰富且美观的折线图,满足多种数据可视化需求。

基础折线图示例

下面示例展示了如何创建一个响应式折线图,包含数据点、颜色和简单动画效果。

js
(function () {
  const ctx = document.getElementById("myChart").getContext("2d");
  const myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: ["一月", "二月", "三月", "四月", "五月", "六月", "七月"],
      datasets: [
        {
          label: "示例数据",
          data: [65, 59, 80, 81, 56, 55, 40],
          fill: false,
          borderColor: "rgb(75, 192, 192)",
          tension: 0.1,
        },
      ],
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true },
        tooltip: { enabled: true },
      },
    },
  });
})();

演示

折线图示例

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>Chart.js 折线图示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 600px; margin: 2rem auto; font-family: Arial, sans-serif; background: #fafafa; padding: 1rem; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  display: block;
  margin: 0 auto;
}

</style> </head>

<body> <canvas id="myChart" width="600" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘myChart’).getContext(‘2d’); const myChart = new Chart(ctx, { type: ‘line’, data: { labels: [‘一月’, ‘二月’, ‘三月’, ‘四月’, ‘五月’, ‘六月’, ‘七月’], datasets: [{ label: ‘示例数据’, data: [65, 59, 80, 81, 56, 55, 40], fill: false, borderColor: ‘rgb(75, 192, 192)’, tension: 0.1 }] }, options: { responsive: true, plugins: { legend: { display: true }, tooltip: { enabled: true } } } }); })(); </script> </body>

</html>

```