我使用chartjs来显示一些虚拟数据作为测试。我总是得到这个错误。这是在实际的Chart.js文件中引起的。
无法读取未定义的属性'length'
下面是我的代码:<canvas id="ctx" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('ctx');
var chart = new Chart(ctx, {
labels: ["1", "2"],
type: 'line',
data: {
datasets: [
{
label: "Test1",
fill: false,
lineTension: 0.1,
backgroundColor: "green",
borderColor: "black",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "black",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "blue",
pointHoverBorderColor: "black",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [1,2,50,42,43,23,1],
spanGaps: false
},
{
label: "Test2",
fill: false,
lineTension: 0.1,
backgroundColor: "blue",
borderColor: "black",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "black",
pointBackgroundColor: "blue",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "green",
pointHoverBorderColor: "black",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [4,55,23,52,32,13,4],
spanGaps: false
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
然而,我实际上不能让这个工作…
在我看来很好,任何建议吗?
在检查了您的代码并与正常运行的代码(取自本网站)进行比较后,问题变得明显了。
首先:你的标签属性与数据的长度不匹配。这也许可以解释你提到的长度问题。
其次,您必须将标签属性移动到数据对象中。
data: {
labels: ["1", "2", "3", "4", "5", "6", "7"],
...
根据您的代码检查此工作示例。
希望能有所帮助。
似乎你需要x轴标签在你的主数据:
data: {
labels : ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
演示