欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

chart.js柱状图

程序员文章站 2022-07-13 16:00:43
...
<canvas id="popChart" width="600" height="400"></canvas>
<script>
	var ctx = $("#popChart");
	var ctx = document.getElementById("popChart");
	var ctx = document.getElementById("popChart").getContext("2d");
	let labels = ['3月', '4月', '5月', '6月', '7月'];
	let data = [99, 80, 99, 99, 99]
	var barChart = new Chart(ctx, {
		type: 'bar',
		data: {
			labels: labels,
			datasets: [{
				label: 'BMI',
				data: data,
				backgroundColor: [
					'rgba(255, 99, 132, 0.6)',
					'rgba(54, 162, 235, 0.6)',
					'rgba(255, 206, 86, 0.6)',
					'rgba(75, 192, 192, 0.6)',
					'rgba(153, 102, 255, 0.6)',
					'rgba(255, 159, 64, 0.6)',
					'rgba(255, 99, 132, 0.6)',
					'rgba(54, 162, 235, 0.6)',
					'rgba(255, 206, 86, 0.6)',
					'rgba(75, 192, 192, 0.6)',
					'rgba(153, 102, 255, 0.6)'
				]
			}]

		},
		options: {
			legend: {
				//除去label
				display: false,
			},
			scales: {
				yAxes: [{
					ticks: {
						//y从零开始
						beginAtZero: true
					}
				}]
			},
			//显示具体数值
			"animation": {
				"duration": 1,
				"onComplete": function() {
					var chartInstance = this.chart,
						ctx = chartInstance.ctx;

					ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
					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];
							ctx.fillText(data, bar._model.x, bar._model.y - 5);
						});
					});
				}
			},

		}
	});
</script>