作者:品味a江湖_232_466 | 来源:互联网 | 2023-01-22 13:36
我想动态设置饼图的每个部分的颜色.由于图表是从数据库动态创建的,我希望每个添加到图表(从数据库)的部分都有不同的颜色.
我试图这样做:
$(document).ready(function() {
$.ajax({
url: "http://localhost/chartjs/projects_chart.php",
method: "GET",
success: function(data) {
console.log(data);
var ict_unit = [];
var efficiency = [];
var dynamicColors = function() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
};
for (var i in data) {
ict_unit.push("ICT Unit " + data[i].ict_unit);
efficiency.push(data[i].efficiency);
var coloR=dynamicColors();
}
var chartData = {
labels: ict_unit,
datasets: [{
label: 'Efficiency ',
//strokeColor:backGround,
backgroundColor: [coloR],
borderColor: 'rgba(200, 200, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: efficiency
}]
};
var ctx = $("#my-canvas");
var barGraph = new Chart(ctx, {
type: 'pie',
data: chartData
})
},
error: function(data) {
console.log(data);
},
});
});
但我只得到饼图第一部分的一种颜色.
你可以帮帮我吗?
1> ɢʀᴜɴᴛ..:
您应该为颜色创建一个单独的数组(就像ict_unit
和它一样efficiency
),而不是每次为coloR
变量指定一个随机颜色值.
以下是您的代码的修订版本:
$(document).ready(function() {
$.ajax({
url: "https://jsonblob.com/api/jsonBlob/a7176bce-84e0-11e7-8b99-016f34757045",
method: "GET",
success: function(data) {
console.log(data);
var ict_unit = [];
var efficiency = [];
var coloR = [];
var dynamicColors = function() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
};
for (var i in data) {
ict_unit.push("ICT Unit " + data[i].ict_unit);
efficiency.push(data[i].efficiency);
coloR.push(dynamicColors());
}
var chartData = {
labels: ict_unit,
datasets: [{
label: 'Efficiency ',
//strokeColor:backGround,
backgroundColor: coloR,
borderColor: 'rgba(200, 200, 200, 0.75)',
//hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: efficiency
}]
};
var ctx = $("#my-canvas");
var barGraph = new Chart(ctx, {
type: 'pie',
data: chartData
})
},
error: function(data) {
console.log(data);
},
});
});