教程 chartjs tutorial

获取 API 数据

在实际项目中,图表数据通常来自远程 API。利用 JavaScript 的 fetch 或其他异步方法,可以获取接口数据后动态更新 Chart.js 图表,实现实时展示最新信息。

以下示例演示通过 fetch 请求模拟接口数据,并更新折线图的数据。

js
const ctx = document.getElementById("apiDataChart").getContext("2d");

const apiChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: [],
    datasets: [
      {
        label: "用户活跃度",
        data: [],
        borderColor: "rgb(54, 162, 235)",
        fill: false,
        tension: 0.1,
      },
    ],
  },
  options: {
    responsive: true,
    plugins: {
      legend: { display: true },
    },
  },
});

// 模拟异步获取数据
fetch("https://jsonplaceholder.typicode.com/posts?_limit=5")
  .then((response) => response.json())
  .then((data) => {
    // 模拟解析数据,使用帖子id和title长度作为示例
    apiChart.data.labels = data.map((item) => "ID " + item.id);
    apiChart.data.datasets[0].data = data.map((item) => item.title.length);
    apiChart.update();
  })
  .catch((err) => {
    console.error("获取数据失败", err);
  });
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>获取 API 数据示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  margin: 1rem auto;
}

</style> </head>

<body> <canvas id="apiDataChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘apiDataChart’).getContext(‘2d’);

  const apiChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: [],
      datasets: [{
        label: '用户活跃度',
        data: [],
        borderColor: 'rgb(54, 162, 235)',
        fill: false,
        tension: 0.1
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true }
      }
    }
  });

  // 模拟异步获取数据
  fetch('https://jsonplaceholder.typicode.com/posts?_limit=5')
    .then(response =&gt; response.json())
    .then(data =&gt; {
      // 模拟解析数据,使用帖子id和title长度作为示例
      apiChart.data.labels = data.map(item =&gt; 'ID ' + item.id);
      apiChart.data.datasets[0].data = data.map(item =&gt; item.title.length);
      apiChart.update();
    })
    .catch(err =&gt; {
      console.error('获取数据失败', err);
    });
})();

</script> </body>

</html>