Chartjs-Chartjs – Doughnut chart with multi layer and running value

0πŸ‘

In case you need a generic solution, you can use the Plugin Core API and define a beforeInit hook that modifies the chart configuration to fit your needs.

Please take a look at below runnable code and see how it could be done.

new Chart('runningValue', {
  type: 'doughnut',
  plugins: [{
    beforeInit: chart => {
      chart.data.datasets = [{
          data: [chart.data.total],
          backgroundColor: chart.data.totalColor,
          borderWidth: 3
        },
        {
          data: [chart.data.complete, chart.data.total - chart.data.complete],
          backgroundColor: [chart.data.completeColor, '#fff'],
          borderWidth: 3
        }
      ]
    }
  }],
  data: {
    total: 50,
    complete: 35,
    totalColor: 'rbg(242, 133, 0)',
    completeColor: 'rgb(255,36,0)'
  },
  options: {
    rotation: -90,
    circumference: 180,
    plugins: {
      legend: {
        display: false
      },
      tooltip: {
        enabled: false
      }
    },
    cutout: '70%'
  }
});
canvas {
  max-height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
<canvas id="runningValue"></canvas>

0πŸ‘

Simply define two values and two background colors on the second dataset as shown in the runnable code below.

const total = 50;
const complete = 35;

new Chart('runningValue', {
  type: 'doughnut',
  data: {
    datasets: [{
        data: [total],
        backgroundColor: 'rbg(242, 133, 0)',
        borderWidth: 3
      },
      {
        data: [complete, total - complete],
        backgroundColor: ['rgb(255,36,0)', '#fff'],
        borderWidth: 3
      }
    ]
  },
  options: {
    rotation: -90,
    circumference: 180,
    plugins: {
      legend: {
        display: false
      },
      tooltip: {
        enabled: false
      }
    },
    cutout: '70%'
  }
});
canvas {
  max-height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
<canvas id="runningValue"></canvas>

Leave a comment