How do i programmatically set bar fillColor in chartJs + angular

đź‘Ť:0

From you question I assume you are using a canvas element.
If so, canvas doesn’t store objects, but a rendered (rasterized) image.

However, you can access canvas-data if you manipulate chart.js helpers function like so:

<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <link rel="icon" href="favicon.ico" typ="image/x-icon">
    <title>Untitled Document</title>
    <meta name="Author" content="" />
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script type="text/javascript" src="http://www.chartjs.org/assets/Chart.js"></script>
    <script src="node_modules/angular-chart.js/dist/angular-chart.min.js"></script>
<script src="node_modules/chart.js/Chart.min.js"></script>
<script src="node_modules/angular-chart.js/dist/angular-chart.min.js"></script>
    <script src="chart_helpers.js"></script>
    <script src="script2.js"></script>
</head>  
<body ng-app="app">
    <div ng-controller="BarCtrl">
        <canvas id="bar" class="chart chart-bar" chart-data="data" chart-labels="labels" colours="custom_colours"> chart-series="series" </canvas>
    </div>  
</body>
</html>

“script2.js”: AngularJs script

angular.module("app", ["chart.js"])
    .controller("BarCtrl", function ($scope) {
      $scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
      $scope.series = ['Series A'];

      $scope.data = [ [65, 59, 80, 81, 56, 55, 40]];

//set your custom colors here using the *fillColor property*
   $scope.custom_colours =  [{fillColor:['#e53a35', '#fef380', '#dcc2aa', '#37617a', '#63c6ae', '#c8c5e5', '#d5ffff']}];
});  

“chart_helpers.js” : chartJs helper manipulation script:

helpers.each(dataset.data, function(dataPoint, index) {
    //This handles each piece of data, getting it ready to draw.
    datasetObject.bars.push(new this.BarClass({
        value: dataPoint,
        label: data.labels[index],
        datasetLabel: dataset.label,
        strokeColor: dataset.strokeColor,
        fillColor: dataset.fillColor[index] || dataset.fillColor,
        highlightFill: dataset.highlightFill || dataset.fillColor,
        highlightStroke: dataset.highlightStroke || dataset.strokeColor
    }));
}, this);

Leave a comment