How set color family to pie chart in chart.js

后端 未结 4 867
春和景丽
春和景丽 2020-12-10 04:31

I am trying to draw a pie chart using Chart.js. My values are coming from a database hence I don\'t know how many values there are going to be in the database. Here I want t

4条回答
  •  情书的邮戳
    2020-12-10 04:46

    Don't waist your time creating a random generator. Instead, pick a few bright pretty colors to loop through.

    This function takes any size and builds an array of background colors using the pallet array.

    function getColors(length){
        let pallet = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
        let colors = [];
    
        for(let i = 0; i < length; i++) {
          colors.push(pallet[i % pallet.length]);
        }
    
        return colors;
      }
    

    You can then set your background colors by calling this function, passing the size of your data as a parameter.

    datasets:
    [
      {
        data: data,
        backgroundColor: getColors(data.length)
      }
    ]
    

    This way your colors are always pretty and every data element is assigned a value.

提交回复
热议问题