0

I have two dataset arrays.

data: [589, 445, 483, 503, 689, 692, 634],
data: [639, 465, 493, 478, 589, 632, 674],

I want to draw every dataset with arrays of color into CSS file.

In my css file, there is :

/* Colors  */
.color0 {
  background-color: red !important;
}
.color1 {
  background-color: lightgray !important;
}

I want to use the colors variable to draw my two array with input color in CSS file. The problem is that the graph bar have black color like what is showing in image as below :

// Color array to draw bar dataset
var colors = ['color0', 'color1'];
var chBar = document.getElementById("chBar");
var chartData = {
  // Label of Entity
  labels: ["RTI_0;RTI", "RTI_1;RTI", "RTI_2;RTI", "BB_0;BB", "BB_1;BB", "BB_2;BB", "BB_3;BB"],
  // Value of percent category RTI|| VSM ...
  datasets: [{
      data: [589, 445, 483, 503, 689, 692, 634],
      backgroundColor: colors[0]
    },
    {
      data: [639, 465, 493, 478, 589, 632, 674],
      xAxisID: 'xAxis1',
      backgroundColor: colors[1]
    }
  ]
};

if (chBar) {
  // new graph
  new Chart(chBar, {
    type: 'bar',
    data: chartData,
    options: {
      scales: {
        xAxes: [{
            barPercentage: 0.7,
            categoryPercentage: 0.3,
            id: 'xAxis1',
            type: "category",
            ticks: {
              callback: function(label) {
                var sublabel_x = label.split(";")[0];
                var label_p = label.split(";")[1];
                return sublabel_x;
              }
            }
          },{
            id: 'xAxis2',
            type: "category",
            gridLines: {
              drawOnChartArea: false, // only want the grid lines for one axis to show up
            },
            ticks: {
              callback: function(label) {
                var sublabel_x = label.split(";")[0];
                var label_p = label.split(";")[1];
                if (label_p === "RTI") {
                  return label_p;
                } else {
                  return label_p;
                }
              }
            }
          }
        ],
        yAxes: [{
          ticks: {
            beginAtZero: false
          },
          scaleLabel: {
            display: true,
            labelString: '%'
          }
        }]
      },
      legend: {
        display: false
      }
    }
  });
}

The output enter image description here

Please help

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • The issue is because you're setting `color0` etc as the `background-color` of the bars, when it should be the `class` instead. Which charting library are you using? – Rory McCrossan Oct 30 '18 at 09:12
  • i use chart.js to draw graph –  Oct 30 '18 at 09:13
  • From their documentation, you need to provide the colour directly in your code, not from CSS through classes or any other selector: http://www.chartjs.org/docs/latest/general/colors.html#colors – Rory McCrossan Oct 30 '18 at 09:16
  • Also in [docs here](https://www.chartjs.org/docs/latest/charts/bar.html#dataset-properties). – skobaljic Oct 30 '18 at 09:17

1 Answers1

0

If you want to give the colors from the style-sheet, you need to traverse the style-sheet from the document and get the colors of the class you want,

Below is the code to traverse the style-sheet and get the colors

function getStyleRuleValue(style, selector, sheet) {
    var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
    for (var i = 0, l = sheets.length; i < l; i++) {
        var sheet = sheets[i];
        if( !sheet.cssRules ) { continue; }
        for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
            var rule = sheet.cssRules[j];
            if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
                return rule.style[style];
            }
        }
    }
    return null;
}

Source: How to get a style attribute from a CSS class by javascript/jQuery?

But it is recomended that use the colors in the JS file itself as per the ChartJS documentation,

So, implementing this in your code works fine.

Here is the code combining your code and the above mentioned code.

function getStyleRuleValue(style, selector, sheet) {
    var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
    for (var i = 0, l = sheets.length; i < l; i++) {
        var sheet = sheets[i];
        if( !sheet.cssRules ) { continue; }
        for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
            var rule = sheet.cssRules[j];
            if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
                return rule.style[style];
            }
        }
    }
    return null;
}

//console.log();



// Color array to draw bar dataset
var colors = [getStyleRuleValue('background-color', '.color0'), getStyleRuleValue('background-color', '.color1')];
var chBar = document.getElementById("chBar");
var chartData = {
  // Label of Entity
  labels: ["RTI_0;RTI", "RTI_1;RTI", "RTI_2;RTI", "BB_0;BB", "BB_1;BB", "BB_2;BB", "BB_3;BB"],
  // Value of percent category RTI|| VSM ...
  datasets: [{
      data: [589, 445, 483, 503, 689, 692, 634],
      backgroundColor: colors[0]
    },
    {
      data: [639, 465, 493, 478, 589, 632, 674],
      xAxisID: 'xAxis1',
      backgroundColor: colors[1]
    }
  ]
};

if (chBar) {
  // new graph
  new Chart(chBar, {
    type: 'bar',
    data: chartData,
    options: {
      scales: {
        xAxes: [{
            barPercentage: 0.7,
            categoryPercentage: 0.3,
            id: 'xAxis1',
            type: "category",
            ticks: {
              callback: function(label) {
                var sublabel_x = label.split(";")[0];
                var label_p = label.split(";")[1];
                return sublabel_x;
              }
            }
          },{
            id: 'xAxis2',
            type: "category",
            gridLines: {
              drawOnChartArea: false, // only want the grid lines for one axis to show up
            },
            ticks: {
              callback: function(label) {
                var sublabel_x = label.split(";")[0];
                var label_p = label.split(";")[1];
                if (label_p === "RTI") {
                  return label_p;
                } else {
                  return label_p;
                }
              }
            }
          }
        ],
        yAxes: [{
          ticks: {
            beginAtZero: false
          },
          scaleLabel: {
            display: true,
            labelString: '%'
          }
        }]
      },
      legend: {
        display: false
      }
    }
  });
}
.color0 {
  background-color: red !important;
}
.color1 {
  background-color: lightgray !important;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>JS Bin</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>

</head>
<body>
  <canvas id="chBar"></canvas>
</body>
</html>

Hope it helps you.

Thank you

chintuyadavsara
  • 1,509
  • 1
  • 12
  • 23
  • Thank for you answer. i got this error when i run you function getStyleRuleValue : Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules –  Oct 30 '18 at 10:03
  • i think that the issue is about href css file. –  Oct 30 '18 at 10:07
  • the href of my file is : custom.css –  Oct 30 '18 at 10:09