gpt4 book ai didi

javascript - Chartjs 饼图每个部分的随机颜色,数据来自数据库动态

转载 作者:可可西里 更新时间:2023-11-01 01:21:53 25 4
gpt4 key购买 nike

我想为饼图的每个部分动态设置颜色。由于图表是从数据库动态创建的,因此我希望(从数据库)添加到图表的每个部分都有不同的颜色。

我正在尝试这样做:

$(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);
},
});
});

但饼图的第一部分只有一种颜色。

你能帮帮我吗?

最佳答案

您应该为颜色创建一个单独的数组(就像ict_unitefficiency ),而不是每次都分配一个随机颜色值到 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);
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="my-canvas"></canvas>

关于javascript - Chartjs 饼图每个部分的随机颜色,数据来自数据库动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45771849/

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