chart.js使用

1.引入js

<script th:src="../Chart.min.js}"></script>

2.页面准备

<div class="row">
	<div class="col-lg-12">
		<div class="ibox ">
			<h5>线图
				<small>  统计</small>
			</h5>
		</div>
		<div class="ibox-content">
			<div id="lineChartDiv">
				<canvas id="lineChart" ></canvas>
			</div>
		</div>
	</div>
</div>
<div class="row">
	<div class="col-lg-12">
	    <div class="ibox ">
	        <div class="ibox-title" style="border: 0px !important;">
	            <h5>饼图
	                <small>统计</small>
	            </h5>
	        </div>
	        <div class="ibox-content">
	            <div id="doughnutChartDiv">
	                <canvas id="doughnutChart"></canvas>
	            </div>
	        </div>
	    </div>
	</div>
</div>
<div class="row">
	<div class="col-lg-12">
	    <div class="ibox ">
	        <div class="ibox-title">
	            <h5>条形图
	                <small>统计</small>
	            </h5>
	        </div>
	        <div class="ibox-content">
	            <div id="barChartDiv">
	                <canvas id="barChart" ></canvas>
	            </div>
	        </div>
	    </div>
	</div>
</div>

线图初始化

	var labels =  ['一月', '二月', '三月', '四月', '五月', '六月', '七月'];
	var data1 =  ['50', '70', '80', '90', '110', '130', '150'];
	
   function lineChart(labels, data1, data2, data3) {
        
            $('#lineChart').remove();
            $('#lineChartDiv').html('<canvas id="lineChart" ></canvas>');
        
            var lineData = {
                labels: labels,
                datasets: [
                    {
                        label: "用户数",
                        backgroundColor: '#9c4153',
                        borderColor: "#9c4153",
                        fill: false,
                        pointBackgroundColor: "#9c4153",
                        pointBorderColor: "#fff",
                        borderWidth:2,
                        data: data1
                    }, {
                        label: "出行数",
                        backgroundColor: '#93ddac',
                        borderColor: "#93ddac",
                        borderWidth:2,
                        fill: false,
                        pointBackgroundColor: "#93ddac",
                        pointBorderColor: "#fff",
                        data: data2
                    }, {
                        label: "下载数",
                        backgroundColor: '#ff6783',
                        borderColor: "#ff6783",
                        borderWidth:2,
                        fill: false,// 隐藏背景色
                        pointBackgroundColor: "#ff6783",
                        pointBorderColor: "#fff",
                        data: data3
                    }
                ]
            };
        
            var lineOptions = {
                responsive: true,
                // showScale: true,
                options: {
                    elements: {
                        line: {
                            tension: 0 //  禁用贝塞尔曲线,没看出实际效果
                        }
                    }
                }
            };
        
            var ctx = document.getElementById("lineChart").getContext("2d");
            new Chart(ctx, {type: 'line', data: lineData, options: lineOptions});
        }

饼图

function doughnutChart(labels,data) {// data数组同上

    $('#doughnutChart').remove(); // this is my <canvas> element
    $('#doughnutChartDiv').html('<canvas id="doughnutChart" ></canvas>');
    
    var doughnutData = {
        labels: labels,
        datasets: [{
            data: data,
            backgroundColor: getColorArr(labels.length, 0.5)  //获取颜色
        }]
    };
    var doughnutOptions = {
        responsive: true  // 页面自适应
    };

    var ctx4 = document.getElementById("doughnutChart").getContext("2d");
    new Chart(ctx4, {type: 'doughnut', data: doughnutData, options: doughnutOptions});
}

柱状图:实现柱状图上展示数据,并转为百分比格式

function batChart(labels, data1, data2) {// 此时data为小数格式

    $('#barChart').remove(); // this is my <canvas> element
    $('#barChartDiv').html('<canvas id="barChart"></canvas>');

    var barData = {
        labels: labels,
        datasets: [
            {
                display: false,
                label: "上线率",
                // backgroundColor: getColorArr(labels.length, 0.5),
                backgroundColor:"#c0b77d",
                borderWidth: 1,
                pointBorderColor: "#c0b77d",
                data: data1
            },
            {
                display: false,
                label: "活跃率",
                // backgroundColor: getColorArr(labels.length, 0.5),
                backgroundColor:"#c04d52",
                borderWidth: 1,
                pointBorderColor: "#c04d52",
                data: data2
            }
        ]
    };

    var barOptions = {
        responsive: true,
        hover: {
            animationDuration: 0  // 防止鼠标移上去,数字闪烁
        },
        title: {                          //图表标题
            display: false,                //是否显示
            position: 'left',            //标题位置
            text: '',                    //标题名
            fontColor: '',                //标题颜色
            fontFamily: '',                //标题字体格式
            fontSize: 10,                  //字体大小
            text: 'hello'
        },
        tooltips: {// 鼠标焦点在柱状图上时,数值转为百分比
            callbacks: {
                label: function (tooltipItem, data) {

                    var label = data.datasets[tooltipItem.datasetIndex].label || '';   
                    if (label) {
                        label += ': ';
                    }
                    label += (tooltipItem.yLabel.toFixed(2) * 100).toFixed(0) + '%';
                    return label;
                }
            }
        },
        animation: {// 柱状图上百分比显示
            onComplete: function () {
                var chartInstance = this.chart, ctx = chartInstance.ctx;
                // 以下属于canvas的属性(font、fillStyle、textAlign...)
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                ctx.fillStyle = "black";
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';

                this.data.datasets.forEach(function (dataset, i) {
                    var meta = chartInstance.controller.getDatasetMeta(i);
                    meta.data.forEach(function (bar, index) {
                        var data = (dataset.data[index].toFixed(2) * 100).toFixed(0) + "%";
                        ctx.fillText(data, bar._model.x, bar._model.y - 5);
                    });
                });
            }
        },
        scales: {

            yAxes: [{
                ticks: {
                    callback: function (label, index, labels) {
                        return label.toFixed(2) * 100 + '%';
                    },
                    beginAtZero: 0,
                    max: 1,
                    min: 0,
                    stepSize: 0.2
                },
                scaleLabel: {
                    display: false,
                    labelString: '',
                },
                gridLines: {
                    display: true
                }
            }
            ]
        }
    };

    var ctx2 = document.getElementById("barChart").getContext("2d");
    new Chart(ctx2, {type: 'bar', data: barData, options: barOptions});
}

获取颜色

// 功能 返回随机的颜色值
// @param opacity 透明度
// @return rgba格式颜色值
var dynamicColors = function (opacity) {
    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    var a = opacity;
    return "rgba(" + r + "," + g + "," + b + "," + a + ")";
};

// 功能 返回rgba格式颜色数组
// @param length 数组的长度
// @param opacity 颜色的透明度
// return 返回rgba数组
var getColorArr = function (length, opacity) {
    var colorArr = new Array();
    for (var i = 0; i < length; i++) {
        colorArr.push(dynamicColors(opacity));
    }
    return colorArr;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值