网站流量分析图表
使用 Chart.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"></script>
<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>
相关内容
- 什么是 Chart.js? Chart.js 是一个简单易用且功能强大的 JavaScript 图表库,支持多种常见图表类型,帮助开发者快速创建美观且响应式的数据可视化效果,适合初学者和专...
- 安装与引入 介绍如何在项目中安装和引入 Chart.js,包括通过 CDN 快速使用和通过 npm 安装到前端构建环境的多种方式,帮助快速搭建图表开发环境。
- 基本结构与初始化 讲解如何创建图表的基本结构与初始化流程,包括配置画布、准备数据和实例化图表的步骤,帮助快速搭建图表展示。
- 示例:折线图 通过示例讲解如何创建折线图,涵盖数据配置、样式设置和基本交互,帮助快速掌握折线图的绘制技巧。
- 折线图 Line 介绍如何使用 Chart.js 创建折线图,详细讲解数据配置、样式调整及交互功能,帮助快速制作趋势图表。
- 柱状图 Bar 介绍如何使用 Chart.js 创建柱状图,详细讲解数据配置、颜色设置及图表样式,帮助快速绘制直观的条形数据展示。