Search code examples
javascripteasypie

Updating Easy Pie Chart


I managed to update easy pie chart, but I don't know how to display the percentage and update it, for example from 1% to 25%, number by number, as the chart updates. Any help?

This is the block of code where I am updating my chart:

var chart = new EasyPieChart(existing, {
  lineWidth: '6',
  barColor: '#fff',
  trackColor: 'rgba(255, 255, 255, 0.5)',
  scaleColor: false,        
});
chart.update(25);

Solution

  • You could use easy-pie-chart's onStep callback function, which will be called on every step to update the number somewhere on the page.

    Also, you probably want to round the number using Math.round

    var element = document.querySelector('.chart');
    var chart = new EasyPieChart(element, {
      lineWidth: '6',
      barColor: '#000',
      trackColor: 'rgba(255, 255, 255, 0.5)',
      scaleColor: true,
      onStep: function(from, to, currentValue) {
        // Inside the callback, 'this.el' refers to 
        // the element that EasyPieChart was created with 
        // - `.chart`
        this.el.querySelector('.number').innerText = `${Math.round(currentValue)}%`;
      },
    });
    
    chart.update(25);
    .chart {
      display: inline-block;
      position: relative;
    }
    
    .number {
      font-size: 1.8rem;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    <div class="chart">
      <span class="number"></span>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/easy-pie-chart/2.1.6/easypiechart.min.js"></script>