gpt4 book ai didi

javascript - 为 ChartJs 中的所有图表设置公共(public)标签和背景颜色

转载 作者:行者123 更新时间:2023-11-30 21:15:51 25 4
gpt4 key购买 nike

大家好,我正在使用 ChartJS用于创建饼图,非常好。在我的项目中,我必须创建许多饼图,所有图表都将具有相同的标签和背景颜色。在下面给出的代码中,我在创建饼图时给出了背景颜色和标签individually.Is there any way to make label and background color common for all the charts.

<!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>

最佳答案

如果从技术上讲,那么是的,有办法。尽管不推荐,因为那不是 ChartJS 的工作方式,因此也没有内置功能。<​​/p>

要实现这一点,您宁愿选择一种骇人听闻的解决方案,也就是使用插件,如下所示:

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>

关于javascript - 为 ChartJs 中的所有图表设置公共(public)标签和背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45695222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com