Chartjs-Redraw the old donut and create a new one by clicking on each color Chart.js

0👍

You just need to do a check before you push a new dataset to make sure you don’t already have 2 datasets.

var ctx = document.getElementById('canvasDoughnut').getContext('2d');
var backgroundColors = [
  '#fd3f4a',
  '#484848',
  '#705bc9',
  '#008ee5',
  '#00c9d8',
  '#5cc600',
  '#ffd939',
  '#ff8f00'

];

var newColors = ['#5cc600', '#ebe9e1'];

var newData = [48, 52];

var varData = [25, 18, 18, 18, 8, 48, 18, 12];

var chart = new Chart(ctx, {
  type: 'doughnut',

  data: {
    datasets: [{

      backgroundColor: backgroundColors,
      data: varData
    }]
  },

  options: {
    cutoutPercentage: 70,
    rotation: Math.PI * -0.7,

    onClick: function(evt, elements) {

      var datasetIndex;
      var dataset;

      if (elements.length) {
        var index = elements[0]._index;
        datasetIndex = elements[0]._datasetIndex;

        // Reset old state
        dataset = chart.data.datasets[datasetIndex];
        dataset.backgroundColor = ['#5cc600', '#ebe9e1'];
        dataset.value = [58, 42],
          dataset.data = [58, 42]

      }
      // config. new data doughnut

      // check to make sure we haven't already pushed a dataset
      if (chart.config.data.datasets.length < 2) {
        chart.config.data.datasets.push({
          backgroundColor: [
            '#5cc600',
            '#ebe9e1'
          ],
          dataPoints: [48, 52],
          data: [48, 52],
        }),
        chart.update();
      }
    } 
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="canvasDoughnut" class="size-doughnut"></canvas>

Leave a comment