问题
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?
回答1:
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?
回答2:
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
来源:https://stackoverflow.com/questions/25778293/chart-js-line-2686-error