教程 chartjs tutorial

网站流量分析图表

使用 Chart.js 可以直观地展示网站流量数据,帮助分析访问量和来源。以下示例结合折线图和柱状图,分别反映每日访问量趋势和主要流量来源。

js
const ctxLine = document.getElementById("trafficLine").getContext("2d");
const trafficLine = new Chart(ctxLine, {
  type: "line",
  data: {
    labels: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    datasets: [
      {
        label: "访问量",
        data: [1200, 1900, 1700, 2100, 2500, 2300, 2000],
        borderColor: "rgb(75, 192, 192)",
        fill: false,
        tension: 0.2,
      },
    ],
  },
  options: {
    responsive: true,
    plugins: { legend: { display: true } },
  },
});

const ctxBar = document.getElementById("trafficBar").getContext("2d");
const trafficBar = new Chart(ctxBar, {
  type: "bar",
  data: {
    labels: ["直接访问", "搜索引擎", "社交媒体", "推荐网站"],
    datasets: [
      {
        label: "访问来源",
        data: [500, 800, 300, 200],
        backgroundColor: [
          "rgba(255, 99, 132, 0.7)",
          "rgba(54, 162, 235, 0.7)",
          "rgba(255, 206, 86, 0.7)",
          "rgba(75, 192, 192, 0.7)",
        ],
      },
    ],
  },
  options: {
    responsive: true,
    plugins: { legend: { display: true } },
  },
});
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>网站流量分析图表示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 900px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

.chart-wrapper {
  width: 100%;
  max-width: 900px;
  margin-bottom: 2rem;
}

canvas {
  background: #fff;
  border: 1px solid #ccc;
  display: block;
  width: 100% !important;
  height: 300px !important;
  margin: 0 auto;
}

</style> </head>

<body> <div class="chart-wrapper"> <canvas id="trafficLine"></canvas> </div> <div class="chart-wrapper"> <canvas id="trafficBar"></canvas> </div> <script> (function () { const ctxLine = document.getElementById(‘trafficLine’).getContext(‘2d’); const trafficLine = new Chart(ctxLine, { type: ‘line’, data: { labels: [‘周一’, ‘周二’, ‘周三’, ‘周四’, ‘周五’, ‘周六’, ‘周日’], datasets: [{ label: ‘访问量’, data: [1200, 1900, 1700, 2100, 2500, 2300, 2000], borderColor: ‘rgb(75, 192, 192)’, fill: false, tension: 0.2 }] }, options: { responsive: true, plugins: { legend: { display: true } } } });

  const ctxBar = document.getElementById('trafficBar').getContext('2d');
  const trafficBar = new Chart(ctxBar, {
    type: 'bar',
    data: {
      labels: ['直接访问', '搜索引擎', '社交媒体', '推荐网站'],
      datasets: [{
        label: '访问来源',
        data: [500, 800, 300, 200],
        backgroundColor: [
          'rgba(255, 99, 132, 0.7)',
          'rgba(54, 162, 235, 0.7)',
          'rgba(255, 206, 86, 0.7)',
          'rgba(75, 192, 192, 0.7)'
        ]
      }]
    },
    options: {
      responsive: true,
      plugins: { legend: { display: true } }
    }
  });
})();

</script> </body>

</html>