简体   繁体   English

饼图仅在我放大时显示

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

I've been trying to display a pie chart, with Chart.js, but it only shows up when there is a change in the dimensions of the canvas.我一直在尝试使用 Chart.js 显示饼图,但它仅在画布尺寸发生变化时才会显示。

The idea is to fetch some data from a RESTAPI and display the information in a pie chart这个想法是从 RESTAPI 获取一些数据并在饼图中显示信息

I found out another answered question, but it uses Ajax which I do not(atleast to my knowledge).我发现了另一个已回答的问题,但它使用了我不知道的 Ajax(至少据我所知)。

Below you may find my code您可以在下面找到我的代码


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta content="ie=edge" http-equiv="X-UA-Compatible">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <title>My Chart.js Chart</title>
</head>
<body>
<div >
    <canvas id="myChart" width="500" height="500"></canvas>
</div>

</body>


<script>
    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))
            data.forEach(country => vCounts.push(country.conflictsCount))
            data.forEach(country => console.log(country.name))
            data.forEach(country => console.log(country.conflictsCount))

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


    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';



</script>
</html>

You need to draw the chart after the fetch has finished and you have processed the data.您需要在fetch完成并处理数据后绘制图表。

So, you can put the chart drawing code in a function and call it inside the then right after processing the data .因此,您可以将图表绘制代码放在一个函数中,并在处理data后立即在then内部调用它。

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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM