条形图中每个条的颜色不同;ChartJS

2022-01-22 00:00:00 javascript chart.js

我在我正在处理的项目中使用 ChartJS,我需要为条形图中的每个条形图使用不同的颜色.

I'm using ChartJS in a project I'm working on and I need a different color for each bar in a Bar Chart.

这是条形图数据集的示例:

Here's an example of the bar chart data set:

var barChartData = {
  labels: ["001", "002", "003", "004", "005", "006", "007"],
  datasets: [{
    label: "My First dataset",
    fillColor: "rgba(220,220,220,0.5)", 
    strokeColor: "rgba(220,220,220,0.8)", 
    highlightFill: "rgba(220,220,220,0.75)",
    highlightStroke: "rgba(220,220,220,1)",
    data: [20, 59, 80, 81, 56, 55, 40]
  }]
};

有什么方法可以不同地绘制每个条吗?

Is there any way to paint each bar differently?

推荐答案

查看 Chart.Bar.js 文件后,我设法找到了解决方案.我用这个函数来生成随机颜色:

After looking into the Chart.Bar.js file I've managed to find the solution. I've used this function to generate a random color:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

我已将它添加到文件的末尾,并在fillColor:"下调用了这个函数

I've added it to the end of the file and i called this function right inside the "fillColor:" under

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

所以现在看起来像这样:

so now it looks like this:

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

                    datasetObject.bars.push(new this.BarClass({
                        value : dataPoint,
                        label : data.labels[index],
                        datasetLabel: dataset.label,
                        strokeColor : dataset.strokeColor,
                        fillColor : getRandomColor(),
                        highlightFill : dataset.highlightFill || dataset.fillColor,
                        highlightStroke : dataset.highlightStroke || dataset.strokeColor
                    }));
                },this);

它的工作原理是我为每个条得到不同的颜色.

and it works I get different color for each bar.

相关文章