Цвет легенды не работает со случайно сгенерированными цветами фона на диаграмме js p ie - PullRequest
1 голос
/ 24 марта 2020

var ctx = document.getElementById('myChart').getContext('2d');

    var labels =  ["Mar-2019","Apr-2019","May-2019","Jun-2019","Jul-2019","Aug-2019","Sep-2019","Oct-2019","Nov-2019","Dec-2019","Jan-2020","Feb-2020","Mar-2020"];
    var dataSet = {"ADVERTS_PUBLISHED":["0","0","1","0","4","0","2","0","1","0","1","1","1"],"ADVERT_ACTIONS":["5","1","2","1","2","0","1","0","1","2","1","0","0"],"VIEWS":["34","1","4","3","5",0,"1",0,"2","5","6",0,0],"CLICKS":["13","0","3","3","3",0,"1",0,"2","4","6",0,0],"SUBMITTED":["3",0,"2","2","2",0,"1",0,"7","3","2",0,0],"PENDING":["0",0,"2","0","0",0,"0","2","0","1","0",0,0],"FILTERED":["3",0,"1","2","2",0,"1","0","7","3","0",0,0],"SHORTLISTED":["0",0,"0","2","0",0,"0","5","0","0","0",0,0],"REGRETTED":["0",0,"0","0","0",0,"0","1","0","0","0",0,0],"INTERVIEWED":["0",0,"0","2","0",0,"0","1","0","0","0",0,0],"OFFERED":["1",0,"0","0","1",0,"11","0","0","0","0",0,0],"OFFERED_AND_DECLINED":["0",0,"0","0","0",0,"0","1","0","0","0",0,0],"REGRETTED_AND_COMM":["0",0,"0","0","0",0,"0","1","0","0","2",0,0],"ACTUAL_HIRED":["0",0,"0","0","0",0,"0","0","0","1","0",0,0]};

myChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Adverts Published',
                        data: dataSet.ADVERTS_PUBLISHED,
                        backgroundColor: function() {
                            return getRandomColorHex()
                        },
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                  //  onClick: graphClickEvent,
                    hover: {
                        onHover: function (e, el) {
                            $("#myChart").css("cursor", el[0] ? "pointer" : "default");
                        }
                    },
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
            
            
            
 function getRandomColorHex() {
        var hex = "0123456789ABCDEF",
            color = "#";
        for (var i = 1; i <= 6; i++) {
            color += hex[Math.floor(Math.random() * 16)];
        }
        return color;
    }           
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="">
   <canvas class="chart__graph" id="myChart"></canvas>
</div>

Я создаю ap ie с использованием диаграммы js, набор данных динамически генерируется из php серверной части и может иметь любой размер поэтому я не могу установить фиксированные цвета для диаграммы p ie.

Мне удалось получить диаграмму p ie, генерирующую случайный цвет фона для каждого раздела, но легенда не принимает цвет фона. Другая проблема заключается в том, что если я использую легенду, чтобы скрыть часть p ie, цвета снова генерируются случайным образом. Я не хочу, чтобы это случилось.

1 Ответ

0 голосов
/ 24 марта 2020

Отправить массив (["red", "blue","orange"] в качестве значения backgroundColor.

Простой forEach пример:

var colors = [];
labels.forEach((element) => {
  var hex_color = getRandomColorHex();
  colors.push(hex_color);
})
console.log(colors) /* ["#5076FA", "#2832C4", "#36DEA3", "#7A940B", "#FD8E0D", "#6214DF", "#9CF566", "#71459C", "#98F6B5", "#B111A4", "#AAB800", "#D8DA57", "#836BD9"] */

И использовать этот массив как значение для backgroundColor:

backgroundColor: colors,

Рабочий пример:

var ctx = document.getElementById('myChart').getContext('2d');

var labels =  ["Mar-2019","Apr-2019","May-2019","Jun-2019","Jul-2019","Aug-2019","Sep-2019","Oct-2019","Nov-2019","Dec-2019","Jan-2020","Feb-2020","Mar-2020"];
var dataSet = {"ADVERTS_PUBLISHED":["0","0","1","0","4","0","2","0","1","0","1","1","1"],"ADVERT_ACTIONS":["5","1","2","1","2","0","1","0","1","2","1","0","0"],"VIEWS":["34","1","4","3","5",0,"1",0,"2","5","6",0,0],"CLICKS":["13","0","3","3","3",0,"1",0,"2","4","6",0,0],"SUBMITTED":["3",0,"2","2","2",0,"1",0,"7","3","2",0,0],"PENDING":["0",0,"2","0","0",0,"0","2","0","1","0",0,0],"FILTERED":["3",0,"1","2","2",0,"1","0","7","3","0",0,0],"SHORTLISTED":["0",0,"0","2","0",0,"0","5","0","0","0",0,0],"REGRETTED":["0",0,"0","0","0",0,"0","1","0","0","0",0,0],"INTERVIEWED":["0",0,"0","2","0",0,"0","1","0","0","0",0,0],"OFFERED":["1",0,"0","0","1",0,"11","0","0","0","0",0,0],"OFFERED_AND_DECLINED":["0",0,"0","0","0",0,"0","1","0","0","0",0,0],"REGRETTED_AND_COMM":["0",0,"0","0","0",0,"0","1","0","0","2",0,0],"ACTUAL_HIRED":["0",0,"0","0","0",0,"0","0","0","1","0",0,0]};

var colors = [];
labels.forEach((element) => {
  var hex_color = getRandomColorHex();
  console.log("hello" + hex_color);
  colors.push(hex_color);
})


var myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: labels,
    datasets: [{
      label: 'Adverts Published',
      data: dataSet.ADVERTS_PUBLISHED,
      backgroundColor: colors,
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    maintainAspectRatio: true,
    //  onClick: graphClickEvent,
    hover: {
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});


function getRandomColorHex() {
  var hex = "0123456789ABCDEF",
      color = "#";
  for (var i = 1; i <= 6; i++) {
    color += hex[Math.floor(Math.random() * 16)];
  }
  return color;
} 
div{
  border: 1px solid red;
}
<div id="">
   <canvas class="chart__graph" id="myChart"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
...