图表 js 图例颜色

chart js graph legend colors

我的图表代码运行良好。我可以使图例的颜色背景取决于 $scope.colours 但对于此示例,我只有 3 个静态数据。但是我这里的问题是我得到的数据是从数据库中获取的。

图表生成的颜色可能应该是图例的背景色吗?

Source Link for chart

var app = angular.module('App', ['chart.js']);

app.controller('Ctrl', function ($scope) { 
   $scope.labels = ["A","B","C"];
   $scope.data = ["1","2","3"];
   $scope.colours = ['#bff0dd', '#ffa67b','#b1c2ff'];
   
   
});
<html ng-app="App" ng-controller="Ctrl">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-chart.js/0.10.2/angular-chart.js"></script>
    </head>
    <body>
     <canvas id="doughnut" class="chart chart-doughnut doughnut-year"
               chart-colours="colours"
                chart-data="data" chart-labels="labels">
               </canvas>   
               
               <h3>Legends</h3>
               <div class="legend-item" ng-repeat="a in colours">
                                                <label>
                                                   A
                                                </label>
                                            </div>
       </body>
    </html>

您可以生成如下颜色代码:

  angular.forEach($scope.data , function (dataItem, index) {
      var colorCode = getColorHex(index);
      $scope.colours.push(colorCode);
  });

  var getColorHex = function (i) {
      //skip black & white
      i+=2;

      var colorDecimal = getRGB(i);
      var colorHex = decimalColorToHTMLcolor(colorDecimal);
      return colorHex;
  }

  function decimalColorToHTMLcolor(colorDecimal) {
      var intnumber = colorDecimal - 0;
      var red, green, blue;
      var template = "#000000";

      red = (intnumber & 0x0000ff) << 16;
      green = intnumber & 0x00ff00;
      blue = (intnumber & 0xff0000) >>> 16;

      intnumber = red | green | blue;
      var HTMLcolor = intnumber.toString(16);
      HTMLcolor = template.substring(0, 7 - HTMLcolor.length) + HTMLcolor;

      return HTMLcolor;
  }

  function getRGB(index) {
      var p = getPattern(index);
      return getElement(p[0]) << 16 | getElement(p[1]) << 8 | getElement(p[2]);
  }

  function getElement(index) {
      var value = index - 1;
      var v = 0;

      for (var i = 0; i < 8; i++) {
          v = v | (value & 1);
          v <<= 1;
          value >>= 1;
      }

      v >>= 1;
      return v & 0xff;
  }

  function getPattern(index) {
      var n = parseInt(Math.cbrt(index));
      index -= (n*n*n);
      var p = [n, n, n];
      if (index == 0) {
          return p;
      }

      index--;
      var v = index % 3;
      index = parseInt(index / 3);
      if (index < n) {
          p[v] = index % n;
          return p;
      }

      index -= n;
      p[v] = parseInt(index / n);
      p[++v % 3] = index % n;
      return p;
  }