我正在尝试将 Chartjs-plugin-annotation 插件与 Chart.js 和 Angular 一起使用。
我基于 Chartjs-plugin-annotation 示例代码构建了一个非常精简的图表,它可以使用直接的 HTML 和 JavaScript 正常工作,显示几个点和一条水平线:
<!doctype html>
<html>
<head>
<script src="./Chart.bundle.js"></script>
<script src="./chartjs-plugin-annotation.js"></script>
</head>
<body>
<div style="width:75%">
<div>
<canvas id="canvas"></canvas>
</div>
</div>
<script>
var scatterChartData = {
datasets: [{
data: [
{ x:0, y:0 },
{ x:10, y:10 },
{ x:5, y:10 }
]
}]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myScatter = Chart.Scatter(ctx, {
data: scatterChartData,
options: {
scales: {
xAxes: [{
}],
yAxes: [{
}]
},
annotation: {
annotations: [{
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-1',
value: 5,
borderColor: 'rgba(255, 0, 0, 0.5)',
borderWidth: 4,
}]
}
}
});
};
</script>
</body>
</html>
但是当我尝试在 Angular 中执行相同的操作时,图表注释不会出现,尽管图表按预期显示:
import { Component, OnInit, ViewChild } from '@angular/core';
import { Chart } from 'chart.js';
import * as annotation from 'chartjs-plugin-annotation';
@Component({
selector: 'app-graphtest',
template: `
<div style="width:75%">
<div>
<canvas #canvas></canvas>
</div>
</div>`
})
export class GraphTest implements OnInit {
constructor() {}
ngOnInit() {
let ctx = this.canvas.nativeElement.getContext('2d');
this.myScatter = Chart.Scatter(
ctx,
{
data: this.scatterChartData,
options: {
scales: {
xAxes: [{
}],
yAxes: [{
}]
},
annotation: {
annotations: [{
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-1',
value: 5,
borderColor: 'rgba(255, 0, 0, 0.5)',
borderWidth: 4,
}]
}
}
}
);
}
@ViewChild('canvas') canvas;
myScatter;
scatterChartData = {
datasets: [{
data: [
{ x:0, y:0 },
{ x:10, y:10 },
{ x:5, y:10 }
]
}]
};
}
有人知道我做错了什么吗?
最佳答案
在 App.module.ts 的导入区域中,粘贴此行
导入'chartjs-plugin-annotation';
关于angular - 图表注释未在 Angular 2 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49119805/