You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用Chart.js读取外部JSON统计动漫喜剧/奇幻品类数量并生成图表

Fixing Your Empty Anime Genre Chart

Hey there, let's get that bar chart working properly—you've got a couple of key issues in your code, mostly around asynchronous data loading and small typos. Here's the breakdown and corrected implementation:

Key Issues in Your Original Code

  • Asynchronous Data Loading: $.getJSON runs in the background, so your loop and chart setup code executes before the JSON data finishes loading. At that point, data is still undefined, so no counts get calculated.
  • Variable Typo: You wrote genress.length instead of genres.length (extra 's')—this throws a reference error that stops your count logic.
  • Mismatched Labels & Variables: Your chart labels reference "Super Natural" but your variable is named fantasy, and you tried using an undefined superNatural variable in the data array.

Corrected Full Code

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <canvas id="myChart"></canvas>
    </div>
    <script>
        // Move all logic inside the getJSON callback to ensure data is loaded first
        $.getJSON("anime.json", function(json) {
            let comedy = 0;
            let fantasy = 0;

            // Iterate over each anime entry
            for (let i = 0; i < json.length; i++) {
                const anime = json[i];
                // Skip if genres don't exist to avoid errors
                if (!anime.genres) continue;
                
                const genres = anime.genres;
                for (let j = 0; j < genres.length; j++) {
                    const value = genres[j].trim().toLowerCase();
                    if (value === 'comedy') {
                        comedy++;
                    }
                    if (value === 'fantasy') {
                        fantasy++;
                    }
                }
            }

            // Initialize the chart now that we have counts
            const myChart = document.getElementById('myChart').getContext('2d');
            new Chart(myChart, {
                type: 'bar',
                data: {
                    labels: ['Comedy', 'Fantasy'], // Aligned with our variables
                    datasets: [{
                        label: 'Anime Count by Genre',
                        data: [comedy, fantasy], // Matched to labels and variables
                        backgroundColor: ['#ffcc00', '#9933ff'], // Optional: add colors for clarity
                        borderColor: ['#cc9900', '#662299'],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Number of Anime'
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: 'Genre'
                            }
                        }
                    }
                }
            });
        });
    </script>
</body>
</html>

What Changed & Why

  1. Async Handling: All data processing and chart initialization is now inside the $.getJSON callback. This guarantees we only work with the data once it's fully loaded from anime.json.
  2. Typo Fix: Corrected genress to genres so the inner loop can iterate over the genre list.
  3. Label/Variable Alignment: Updated chart labels to match our comedy and fantasy variables, and fixed the data array to use the correct variable names.
  4. Error Prevention: Added a check for anime.genres to skip entries that don't have a genre list (avoids potential errors if your JSON has incomplete entries).
  5. Optional Enhancements: Added basic colors and axis titles to make the chart more readable—feel free to adjust these to your preference.

内容的提问来源于stack exchange,提问作者user13150038

火山引擎 最新活动