我最近将chart.js添加到了我的5个角项目中,我试图创建一个线型图表,但我在浏览器控制台中有一个错误:Failed to create a chart: can't acquire context from the given item
如何解决这个问题?
public chart = [];
ngOnInit() {
this.chart = new Chart('canvas', {
type: 'line',
data: {
labels: ["a", "b", "c", "d", "e"],
datasets: [
{
title: "Some Data",
values: [25, 40, 30, 35, 100],
borderColor: "#3cba9f",
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}],
}
}
});
}
组件html:
<div *ngIf="chart">
<canvas #canvas id="canvas">{{ chart }}</canvas>
</div>
答案 0 :(得分:3)
问题是* ngIf。只要* ngIf == false,画布就会存在,因此chart.js无法找到它。将标签更改为,它应该工作
<div [hidden]="!chart">
<canvas id="canvas">{{ chart }}</canvas>
</div>
答案 1 :(得分:2)
正如documentation所说:
要创建图表,我们需要实例化Chart类。去做这个, 我们需要传入节点,jQuery实例或者2d上下文 我们想要绘制图表的画布
所以你的代码应该是这样的:
var canvas = <HTMLCanvasElement> document.getElementById("canvas");
var ctx = canvas.getContext("2d");
this.chart = new Chart(ctx, {
type: 'line',
data: {
labels: ["a", "b", "c", "d", "e"],
datasets: [
{
title: "Some Data",
values: [25, 40, 30, 35, 100],
borderColor: "#3cba9f",
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}],
}
}
});
}