ChartJS 画布未在页面上显示图表

pnwntuvh  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(197)

我在系统中有不同的图表来可视化反馈数据使用Canvas和ChartJs。所有其他的反馈可视化,如学生,教师等是可见的,但毕业生反馈数据是不可视化的。
下面的代码并没有显示图表

<h3 style="text-align: center; background-color: lightgrey;">Graduate Student Feedback Visualization</h3>

        <canvas id="graduate-chart1" class="mx-auto" style="width:100%;max-width:600px"></canvas>
        <br> 
        <canvas id="graduate-chart2" class="mx-auto" style="width:100%;max-width:600px"></canvas>
        <br>
        <canvas id="graduate-chart3" class="mx-auto" style="width:100%;max-width:600px"></canvas>
        <br>
        <canvas id="graduate-chart4" class="mx-auto" style="width:100%;max-width:600px"></canvas>
        <br>
        <canvas id="graduate-chart5" class="mx-auto" style="width:100%;max-width:600px"></canvas>
        //upto 16
        <canvas id="graduate-chart16" class="mx-auto" style="width:100%;max-width:600px"></canvas>

这是脚本

<script>

        var xValues = ["very satisfied", "satisfied", "neutral", "dissatisifed", "very dissatified"];
        var yValues = {{ Graduate_Feedback_data }};
        var barColors = [
            "#b91d47",
            "#00aba9",
            "#2b5797",
            "#e8c3b9",
            "#1e7145"
        ];

        graduate_questionnaire = ["The work in the program is too heavy and induces a lot of pressure.",
                                "The program is effective in enhancing team- working abilities.",
                                 /// some more questions here
                                "Discipline",
                                "The link between theory and practice"]
        graduate_chart_ids = ["graduate-chart1", "graduate-chart2", "graduate-chart3", "graduate-chart4", "graduate-chart5", "graduate-chart6", "graduate-chart7", "graduate-chart8", "graduate-chart9","graduate-chart10", "graduate-chart11", "graduate-chart12", "graduate-chart13","graduate-chart14","graduate-chart15",'graduate-chart16']
        for (let i = 0; i < graduate_chart_ids.length; i++) {
            new Chart(graduate_chart_ids[i], {
                type: "pie",
                data: {
                    labels: xValues,
                    datasets: [{
                        backgroundColor: barColors,
                        data: yValues[i]
                    }]
                },
                options: {
                    title: {
                        display: true,
                        text: graduate_questionnaire[i]
                    }
                }

            }

            )
        }
    </script>
nfzehxib

nfzehxib1#

您的脚本在dom完全构建之前运行,这意味着canvas元素还不存在,因此chart.js尝试获取一些不可用的内容。
要解决这个问题,你需要确保脚本在你的dom完全加载后运行。有多种方法可以做到这一点,如this so answer中所述。
来自链接的答案:
这些解决方案将奏效:
如注解中所述,使用defer:

<script src="deferMe.js" defer></script>

<body onload="script();">

document.onload = function ...

或者甚至

window.onload = function ...

相关问题