Chart.js line 2686 Error

2019-08-27 16:04发布

I want lineChart of Chart.js in my sinatra application. But firefox console says

`TypeError:this.scale is undefined(Chart.js:2686)`

and, lineChart is not displayed.I wrote following code.

@hello.erb

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
        <script src="Chartjs/Chart.js" type="text/javascript"></script>
        <script src="script.js" type="text/javascript"></script>
    </head>
    <body>
        <canvas id="line" height="450" width="600"></canvas>
    </body>
</html>

@script.js

$(function(){
    var lineChartData = {
    labels : ["hoge","fuga"],
    datasets : [
    {
        fillColor : "rgba(220,220,220,0.5)",
        strokeColor : "rgba(220,220,220,1)",
        pointColor : "rgba(220,220,220,1)",
        pointStrokeColor : "#fff",
        data : [60,70]
    } ]
}

var myLine = new Chart(document.getElementById("line").getContext("2d")).Line(lineChartData);
});

When I write this code in NOT sinatra(erb), it works correctly. What should I do modify?

2条回答
看我几分像从前
2楼-- · 2019-08-27 16:18

Your Problem looks like a timing problem. Since your canvas element is not present when your script runs.

With Jquery you can just wrap your chart statement in a document.ready

$( document ).ready(function() {
     var myLine = new Chart(document.getElementById("line").getContext("2d")).Line(lineChartData);
}

For a non Jquery solution I recommend https://stackoverflow.com/a/9899701/1279355

查看更多
够拽才男人
3楼-- · 2019-08-27 16:33

Check the developer tools of your browser (often, press F12) and see in the Network tab if the files are loaded correctly - press F5 to reload the page. It might be that your script files are not loaded, in that case prepend a slash (<script src='/script.js' ...>) . Are the javascript files located in your public directory?

查看更多
登录 后发表回答