设置ChartJ中所有图表的常用标签和背景颜色

时间:2017-08-15 14:40:06

标签: javascript charts chart.js

大家好我使用ChartJS创建饼图,非常好。在我的项目中我必须创建许多饼图,所有图表都将具有相同的标签和背景颜色。在给出的代码中下面我给出了backgroundColor和label,同时单独创建饼图。有没有办法让所有图表都有标签和背景颜色。



<!DOCTYPE html>
<html>
<head>
	<title> ChartJS tutorial </title>
	<style type="text/css">
        #pie-charts-wrapper{
        	width:1000px;
        	margin-left:auto;
        	margin-right:auto;
        }
        .pie-chart-wrapper{
        	width:500px;
        	height:300px;
        	box-sizing:border-box;
        	float:left;
        	padding:20px;
        }
	</style>
</head>
<body>
    
    <div id="pie-charts-wrapper">
       <div class="pie-chart-wrapper">
          <canvas id="pieChart1" width="500px" height="300" ></canvas>
       </div>
       <div class="pie-chart-wrapper">
          <canvas id="pieChart2" width="500px" height="300" ></canvas>
       </div>
    </div>       

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" ></script>
    <script type="text/javascript">
        var ctx1 = document.getElementById("pieChart1");
        var ctx2 = document.getElementById("pieChart2");

		var data1 = {
		    labels: ['Signed','Not Signed'],
		    datasets: [{
		    	backgroundColor:['#1abc9c','#34495e'],
		      data: [10, 25],
		    }],
		};

		var data2 = {
		    labels: ['Signed','Not Signed'],
		    datasets: [{
		    	backgroundColor:['#1abc9c','#34495e'],
		      data: [15, 2]
		    }],
		};

		var myPieChart1 = new Chart(ctx1,{
		    type: 'pie',
		    data: data1
		});

		var myPieChart2 = new Chart(ctx2,{
		    type: 'pie',
		    data: data2
		});
    </script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

如果在技术上说话然后,就有办法。虽然不推荐,因为不是ChartJS的工作方式,因此也没有内置功能。<​​/ p>

要做到这一点,你宁愿选择一种hacky解决方案,即使用插件,如下所示:

Chart.plugins.register({
   beforeInit: function(chart) {
      chart.data.labels = ['Signed', 'Not Signed'];
      chart.data.datasets[0].backgroundColor = ['#1abc9c', '#34495e'];
   }
});

*在脚本开头添加

ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇ

Chart.plugins.register({
   beforeInit: function(chart) {
      chart.data.labels = ['Signed', 'Not Signed'];
      chart.data.datasets[0].backgroundColor = ['#1abc9c', '#34495e'];
   }
});

var ctx1 = document.getElementById("pieChart1");
var ctx2 = document.getElementById("pieChart2");

var data1 = {
   datasets: [{
      data: [10, 25],
   }]
};

var data2 = {
   datasets: [{
      data: [15, 2]
   }]
};

var myPieChart1 = new Chart(ctx1, {
   type: 'pie',
   data: data1
});

var myPieChart2 = new Chart(ctx2, {
   type: 'pie',
   data: data2
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="pieChart1" width="500px" height="300"></canvas>
<canvas id="pieChart2" width="500px" height="300"></canvas>