Chart.js: chart not displayed

半城伤御伤魂 提交于 2020-01-10 21:45:06

问题


I'd like to use Chart.js to create stunning charts into a webpage.

Following the documentation, I wrote the code as follows:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8"/>
    <title>Chart.js demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
</head>

<body>
    <script>
        var pieData = [
            {
                value: 20,
                color:"#878BB6"
            },
            {
                value : 40,
                color : "#4ACAB4"
            },
            {
                value : 10,
                color : "#FF8153"
            },
            {
                value : 30,
                color : "#FFEA88"
            }
        ];
        // Get the context of the canvas element we want to select
        var countries= document.getElementById("countries").getContext("2d");
        new Chart(countries).Pie(pieData);
    </script>

    <h1>Chart.js Sample</h1>
    <canvas id="countries" width="600" height="400"></canvas>
</body>

</html>

Which is the reason why the chart doesn't appear?


回答1:


First, you have to put your script after the canvas declaration. After that, delete the pie options (or define them).

<html>
<head>
    <meta charset="utf-8"/>
    <title>Chart.js demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
</head>
<body>


    <h1>Chart.js Sample</h1>

    <canvas id="countries" width="600" height="400"></canvas>
    <script>
        var pieData = [
            {
                value: 20,
                color:"#878BB6"
            },
            {
                value : 40,
                color : "#4ACAB4"
            },
            {
                value : 10,
                color : "#FF8153"
            },
            {
                value : 30,
                color : "#FFEA88"
            }
        ];
        // Get the context of the canvas element we want to select
        var countries= document.getElementById("countries").getContext("2d");
        new Chart(countries).Pie(pieData);
    </script>
</body>




回答2:


Add a div outside the canvas element:

<div><canvas id="countries" width="600" height="400"></canvas></div>



回答3:


pieOptions is null :) just remove it from your .Pie() call.

http://jsbin.com/decagicu/1/

And keep your browser script console open, so you can see all the valuable output it provides you :)



来源:https://stackoverflow.com/questions/24865501/chart-js-chart-not-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!