[Chartjs]-Pie Chart shows up only when I zoom in-out

0👍

You need to draw the chart after the fetch has finished and you have processed the data.

So, you can put the chart drawing code in a function and call it inside the then right after processing the data.

var ctx = document.getElementById('myChart').getContext('2d');
var vNames = [];
var vCounts = [];
fetch('/Conflicts/conflictsOnAllCountries')
  .then(response => response.json())
  .then(data => {

    data.forEach(country => {
      vNames.push(country.name)
      vCounts.push(country.conflictsCount)
    });

    drawChart();
  })
  .catch(err => {
    console.error('Fetch error:', err);
  });

function drawChart() {
  var myChart = new Chart(ctx, {
    type: 'pie', // bar, horizontalBar, pie, line, doughnut, radar, polarArea
    data: {

      labels: vNames,
      datasets: [{
        label: 'Conflicts',
        data: vCounts,
        //backgroundColor:'green',
        backgroundColor: [
          'rgba(255, 99, 132, 0.6)',
          'rgba(54, 162, 235, 0.6)',
          'rgba(255, 206, 86, 0.6)',
          'rgba(75, 192, 192, 0.6)',
          'rgba(153, 102, 255, 0.6)',
          'rgba(255, 159, 64, 0.6)',
          'rgba(255,173,155,0.6)',
          'rgba(146,255,78,0.6)',
          'rgba(113,255,219,0.6)'

        ],
        borderWidth: 1,
        borderColor: '#777',
        hoverBorderWidth: 3,
        hoverBorderColor: '#000'
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Conflicts/Country',
        fontSize: 25
      },
      legend: {
        display: true,
        position: 'right',
        labels: {
          fontColor: '#000'
        }
      },
      layout: {
        padding: {
          left: 50,
          right: 50,
          bottom: 50,
          top: 50
        }
      },
      tooltips: {
        enabled: true
      }
    }
  });
}


// Global Options
Chart.defaults.global.defaultFontFamily = 'Lato';
Chart.defaults.global.defaultFontSize = 15;
Chart.defaults.global.defaultFontColor = '#777';

Leave a comment