昨天有个朋友给了我一个博客,让我给他加一些功能,其中一个是实现网站访问量统计,用折线图显示最近两周的情况。
今天上午写了一下,效果图如下
前端绘制统计图,最先想到的就是Chart.js,直达官网
折线图参考了官网的例子:点此直达
具体实现如下
1.引入库
前面两个直接用cdn,后面那个 utils.js 代码如下(可以在上面那个例子里下载,点此直达)
修改了里面第127行的获得数据的代码实现,例子里的是获得随机值,这里我们需要从数据库查询
完整的 utils.js 代码如下,主要关注 126-135行
2.HTML代码
3.js 代码
今天上午写了一下,效果图如下
前端绘制统计图,最先想到的就是Chart.js,直达官网
折线图参考了官网的例子:点此直达
具体实现如下
前端代码
1.引入库
- <script src="https://cdn.bootcss.com/jquery/1.12.3/jquery.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js" ></script>
- <script src="/js/utils.js" ></script>
前面两个直接用cdn,后面那个 utils.js 代码如下(可以在上面那个例子里下载,点此直达)
修改了里面第127行的获得数据的代码实现,例子里的是获得随机值,这里我们需要从数据库查询
完整的 utils.js 代码如下,主要关注 126-135行
- 'use strict';
- window.chartColors = {
- red: 'rgb(255, 99, 132)',
- orange: 'rgb(255, 159, 64)',
- yellow: 'rgb(255, 205, 86)',
- green: 'rgb(75, 192, 192)',
- blue: 'rgb(54, 162, 235)',
- purple: 'rgb(153, 102, 255)',
- grey: 'rgb(201, 203, 207)'
- };
- (function (global) {
- var MONTHS = [
- 'January',
- 'February',
- 'March',
- 'April',
- 'May',
- 'June',
- 'July',
- 'August',
- 'September',
- 'October',
- 'November',
- 'December'
- ];
- var COLORS = [
- '#4dc9f6',
- '#f67019',
- '#f53794',
- '#537bc4',
- '#acc236',
- '#166a8f',
- '#00a950',
- '#58595b',
- '#8549ba'
- ];
- var Samples = global.Samples || (global.Samples = {});
- var Color = global.Color;
- Samples.utils = {
- // Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
- srand: function (seed) {
- this._seed = seed;
- },
- rand: function (min, max) {
- var seed = this._seed;
- min = min === undefined ? 0 : min;
- max = max === undefined ? 1 : max;
- this._seed = (seed * 9301 + 49297) % 233280;
- return min + (this._seed / 233280) * (max - min);
- },
- numbers: function (config) {
- var cfg = config || {};
- var min = cfg.min || 0;
- var max = cfg.max || 1;
- var from = cfg.from || [];
- var count = cfg.count || 8;
- var decimals = cfg.decimals || 8;
- var continuity = cfg.continuity || 1;
- var dfactor = Math.pow(10, decimals) || 0;
- var data = [];
- var i, value;
- for (i = 0; i < count; ++i) {
- value = (from[i] || 0) + this.rand(min, max);
- if (this.rand() <= continuity) {
- data.push(Math.round(dfactor * value) / dfactor);
- } else {
- data.push(null);
- }
- }
- return data;
- },
- labels: function (config) {
- var cfg = config || {};
- var min = cfg.min || 0;
- var max = cfg.max || 100;
- var count = cfg.count || 8;
- var step = (max - min) / count;
- var decimals = cfg.decimals || 8;
- var dfactor = Math.pow(10, decimals) || 0;
- var prefix = cfg.prefix || '';
- var values = [];
- var i;
- for (i = min; i < max; i += step) {
- values.push(prefix + Math.round(dfactor * i) / dfactor);
- }
- return values;
- },
- months: function (config) {
- var cfg = config || {};
- var count = cfg.count || 12;
- var section = cfg.section;
- var values = [];
- var i, value;
- for (i = 0; i < count; ++i) {
- value = MONTHS[Math.ceil(i) % 12];
- values.push(value.substring(0, section));
- }
- return values;
- },
- color: function (index) {
- return COLORS[index % COLORS.length];
- },
- transparentize: function (color, opacity) {
- var alpha = opacity === undefined ? 0.5 : 1 - opacity;
- return Color(color).alpha(alpha).rgbString();
- }
- };
- // 获得数据,参数date为0表示获得今天的访问量,1表示昨天,2表示前天,以此类推
- window.getViewCount = function (date) {
- var result = 0;
- $.ajax({
- url: "/admin/views/" + date, async: false, success: function (data) {
- result = data;
- }
- });
- return result;
- };
- window.getViewCount2 = function () {
- return Math.round(Samples.utils.rand(0, 10000));
- };
- // INITIALIZATION
- Samples.utils.srand(Date.now());
- // Google Analytics
- /* eslint-disable */
- if (document.location.hostname.match(/^(www\.)?chartjs\.org$/)) {
- (function (i, s, o, g, r, a, m) {
- i['GoogleAnalyticsObject'] = r;
- i[r] = i[r] || function () {
- (i[r].q = i[r].q || []).push(arguments)
- }, i[r].l = 1 * new Date();
- a = s.createElement(o),
- m = s.getElementsByTagName(o)[0];
- a.async = 1;
- a.src = g;
- m.parentNode.insertBefore(a, m)
- })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
- ga('create', 'UA-28909194-3', 'auto');
- ga('send', 'pageview');
- }
- /* eslint-enable */
- }(this));
2.HTML代码
- <div style="width:100%;">
- <canvas id="canvas"></canvas>
- </div>
3.js 代码
- <script>
- // 获取最近14天时间
- var DAYS = (function(){
- // 14天
- var arr = [];
- var newdate = new Date();//当前日期
- var year = newdate.getFullYear();//当前年份
- var month = newdate.getMonth()+1;//当前月份
- var now = newdate.getTime();//今天时间戳
- var nowDay = newdate.getDate();//今天是一个月的第几天(1-32)
- var oneDayTime = 60*60*24*1000;
- for(var i=0; i<14; i++){
- var d = new Date(now - i*oneDayTime);
- var dd = d.getDate();
- if((nowDay -i) < 1) {
- month = d.getMonth()+1;
- }
- arr.push(year+'-'+month+'-'+(dd < 10 ? '0' + dd : dd + ''));
- }
- return arr.reverse();
- })();
- var config = {
- type: 'line',
- data: {
- labels: DAYS,
- datasets: [{
- label: '访问量',
- backgroundColor: window.chartColors.red,
- borderColor: window.chartColors.red,
- data: [
- getViewCount(13),
- getViewCount(12),
- getViewCount(11),
- getViewCount(10),
- getViewCount(9),
- getViewCount(8),
- getViewCount(7),
- getViewCount(6),
- getViewCount(5),
- getViewCount(4),
- getViewCount(3),
- getViewCount(2),
- getViewCount(1),
- getViewCount(0)
- ],
- fill: false,
- }]
- },
- options: {
- responsive: true,
- title: {
- display: true,
- text: '两周内访问量统计'
- },
- tooltips: {
- mode: 'index',
- intersect: false,
- },
- hover: {
- mode: 'nearest',
- intersect: true
- },
- scales: {
- xAxes: [{
- display: true,
- scaleLabel: {
- display: true,
- labelString: '日期'
- }
- }],
- yAxes: [{
- display: true,
- scaleLabel: {
- display: true,
- labelString: '访问量'
- },
- ticks: {
- callback: function(value, index, values) {
- return value;
- }
- },
- }]
- }
- }
- };
- window.onload = function() {
- var ctx = document.getElementById('canvas').getContext('2d');
- window.myLine = new Chart(ctx, config);
- };
- </script>
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏