最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to dynamically set backgroundColor and borderColor barchart unsing Chart.js - Stack Overflow

programmeradmin3浏览0评论

I am trying to set the backgroundColor and borderColor based on the dynamic data I get, I am also trying to alternate the color if the "score" number is even or odd I can't find a way to get it done. Any suggestions is very appreciated.

    <!DOCTYPE html>
    <html>
        <head>
            <title>ChartJS - BarGraph</title>
            <style type="text/css">
                #chart-container {
                    width: 800px;
                    height: 600px;
                }
            </style>
            <!-- javascript -->
    <script type="text/javascript" src="jquery-1.11.min.js"></script>
    <script type="text/javascript" src="Chart.min.js"></script>

    <script type="text/javascript">

    $(document).ready(function(){
    $.ajax({
        //url: "test.html",
        //method: "GET",

    success: function(data) {
                // test data
        var data = [
            {  
                "Serverid":"1",
                "score":"37"
            },
            {  
                "Serverid":"2",
                "score":"60"
            },
            {  
                "Serverid":"3",
                "score":"35"
            },
            {  
                "Serverid":"4",
                "score":"41"
            },
            {  
                "Serverid":"5",
                "score":"50"
            },
                {  
                "Serverid":"6",
                "score":"70"
            }
            // ... it can be more than that
            ];
        var Server = [];
        var score = [];

        for(var i in data) {
        Server.push("Server " + data[i].Serverid);
        score.push(data[i].score);
        }
    var chartdata = {

        labels: Server,
        datasets : [

        {
        label: 'Score I',

        backgroundColor: [

            // even color
        'rgba(255, 99, 132, 0.2)',
        // odd color
            'rgba(75, 192, 192, 0.2)'

        ],

        borderColor: [
            // even color
        'rgba(255,99,132,1)',
        // odd color
        'rgba(153, 102, 255, 1)'
        ],

        borderWidth: 1,
        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
        hoverBorderColor: 'rgba(200, 200, 200, 1)',
        data: score
        }
                    ]
    };

    var ctx = $("#mycanvas");

    var barGraph = new Chart(ctx, {
                    type: 'bar',
                    data: chartdata,
                    options: {
                        scales: {
                            yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                        }
                                }]
                            }
                        }
                    });
    }, // end success
    error: function(data) {
                console.log(data);
                alert(data);
                }
    }); // end ajax

    });

    </script>
        </head>
        <body>

    <br> Test Bar 3 <br>
            <div id="chart-container">
                <canvas id="mycanvas"></canvas>
            </div>



    </body>
    </html>

Thank you!

I am trying to set the backgroundColor and borderColor based on the dynamic data I get, I am also trying to alternate the color if the "score" number is even or odd I can't find a way to get it done. Any suggestions is very appreciated.

    <!DOCTYPE html>
    <html>
        <head>
            <title>ChartJS - BarGraph</title>
            <style type="text/css">
                #chart-container {
                    width: 800px;
                    height: 600px;
                }
            </style>
            <!-- javascript -->
    <script type="text/javascript" src="jquery-1.11.min.js"></script>
    <script type="text/javascript" src="Chart.min.js"></script>

    <script type="text/javascript">

    $(document).ready(function(){
    $.ajax({
        //url: "test.html",
        //method: "GET",

    success: function(data) {
                // test data
        var data = [
            {  
                "Serverid":"1",
                "score":"37"
            },
            {  
                "Serverid":"2",
                "score":"60"
            },
            {  
                "Serverid":"3",
                "score":"35"
            },
            {  
                "Serverid":"4",
                "score":"41"
            },
            {  
                "Serverid":"5",
                "score":"50"
            },
                {  
                "Serverid":"6",
                "score":"70"
            }
            // ... it can be more than that
            ];
        var Server = [];
        var score = [];

        for(var i in data) {
        Server.push("Server " + data[i].Serverid);
        score.push(data[i].score);
        }
    var chartdata = {

        labels: Server,
        datasets : [

        {
        label: 'Score I',

        backgroundColor: [

            // even color
        'rgba(255, 99, 132, 0.2)',
        // odd color
            'rgba(75, 192, 192, 0.2)'

        ],

        borderColor: [
            // even color
        'rgba(255,99,132,1)',
        // odd color
        'rgba(153, 102, 255, 1)'
        ],

        borderWidth: 1,
        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
        hoverBorderColor: 'rgba(200, 200, 200, 1)',
        data: score
        }
                    ]
    };

    var ctx = $("#mycanvas");

    var barGraph = new Chart(ctx, {
                    type: 'bar',
                    data: chartdata,
                    options: {
                        scales: {
                            yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                        }
                                }]
                            }
                        }
                    });
    }, // end success
    error: function(data) {
                console.log(data);
                alert(data);
                }
    }); // end ajax

    });

    </script>
        </head>
        <body>

    <br> Test Bar 3 <br>
            <div id="chart-container">
                <canvas id="mycanvas"></canvas>
            </div>



    </body>
    </html>

Thank you!

Share asked Mar 7, 2017 at 19:26 MaresiaMaresia 772 gold badges2 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

There isn't really anything special that is required to dynamically set your bar background and border colors, it all just depends on what logic you want to use to set the colors.

Per the API, chart.js allows you to pass in an array of colors (instead of just a simple color) in your bar chart dataset for backgroundColor and borderColor. You can control data point colors because the index in this array maps to the index in your data array. In other words, if you want to color the 2nd data point blue, then insert blue into the 2nd index of the color array.

So all you need to do is iterate over your dynamic data and build your data, backgroundColor, and borderColor arrays per your logic (alternating colors). Here is an example.

function getData(data) {
  var dataSize = Math.round(Math.random() * 100);
  var evenBackgroundColor = 'rgba(255, 99, 132, 0.2)';
  var evenBorderColor = 'rgba(255,99,132,1)';
  var oddBackgroundColor = 'rgba(75, 192, 192, 0.2)';
  var oddBorderColor = 'rgba(153, 102, 255, 1)';

  var labels = [];

  var scoreData = {
    label: 'Mid-Term Exam 1',
    data: [],
    backgroundColor: [],
    borderColor: [],
    borderWidth: 1,
    hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
    hoverBorderColor: 'rgba(200, 200, 200, 1)',
  };

  for (var i = 0; i < dataSize; i++) {
    scoreData.data.push(window.randomScalingFactor());
    labels.push("Score " + (i + 1));

    if (i % 2 === 0) {
      scoreData.backgroundColor.push(evenBackgroundColor);
      scoreData.borderColor.push(evenBorderColor);
    } else {
      scoreData.backgroundColor.push(oddBackgroundColor);
      scoreData.borderColor.push(oddBorderColor);
    }
  }

  return {
    labels: labels,
    datasets: [scoreData],
  };
};

Here is a codepen example demonstrating what I mean.

Now, to map this back to your specific example, you would simply call your getData() method from within your $.ajax success callback (or just copy the essence of my example directly into your callback). Here is an example of what your code (supplied from your question) would look like calling the above getData() function.

<script type="text/javascript">
  $(document).ready(function() {
    $.ajax({
      //url: "test.html",
      //method: "GET",
      success: function(data) {   
        var ctx = $("#mycanvas");

        // create our chart and pass it the data returned from the ajax request
        var barGraph = new Chart(ctx, {
          type: 'bar',

          // pass the data returned from the ajax request so we can assemble it
          data: getData(data),
          options: {
            scales: {
              yAxes: [{
                ticks: {
                  beginAtZero: true
                }
              }]
            }
          }
        });
      }, // end success
      error: function(data) {
        console.log(data);
        alert(data);
      }
    }); // end ajax
  });
</script>

Or just take a look at this other example showing the solution mapped to your code.

 public class TheServerController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        //Json Function To Call The Data
        public JsonResult DummyServerData()
        {
            List<TheServer> allDummyServers = ServerRepository.GetAllServers();
            Chart _chart = new Chart();
            //Create And Load Server-Names-Array
            _chart.labels = allDummyServers.Select(x => x.ServerId).ToArray();
            //Create Scores-Array
            int[] scores = allDummyServers.Select(x => x.Score).ToArray();
            //Create An Empty-Colors-Array With The Same Size As Scores.Count
            string[] colours = new string[scores.Length];
            for (int i = 0; i < scores.Length; i++)
            {
                //Load The Colours-Array With As Per Index(i) Of The Scores-Array 
                //By Calling The Coloring Function From Repository
                colours[i] = ServerRepository.GetColourStringNameBasedOnScore(scores[i]);
            }
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new List<Datasets>();
            _dataSet.Add(new Datasets()
                {
                    label = "Server Scores",
                    data = scores,// Adding The Scores To Dataset
                    backgroundColor = colours,// Adding The Colours To Dataset
                    borderWidth = "1"
                });
                _chart.datasets = _dataSet;
            return Json(_chart, JsonRequestBehavior.AllowGet);
            }
    }
发布评论

评论列表(0)

  1. 暂无评论