我在我的angular 6+项目中使用了ChartJs,但是当我使用chartjs-plugin-crosshair时,它不起作用。我正在使用ChartJs 2.8.0。
这是图表的ts文件。
非常感谢。
import { Component, OnInit } from '@angular/core';
import { Chart } from 'Chart.js';
@Component({
selector: 'my-app',
template:`
<div>
<canvas id="myChart" width="600" height="400"></canvas>
</div>
`,
styleUrls: ['./line-custom-tooltips.component.scss']
})
export class LineCustomTooltipsComponent implements OnInit {
lineChart: Chart;
ctx: any;
ngOnInit() {
this.drawMyChart();
}
drawChart() {
this.lineChart = document.getElementById("myChart");
this.ctx = this.lineChart.getContext("2d");
this.lineChart = new Chart(this.ctx, {
type: "scatter",
options: {
plugins: {
crosshair: {
sync: {
enabled: false
}
}
},
tooltips: {
mode: "interpolate",
intersect: false,
callbacks: {
title: function (a, d) {
return a[0].xLabel.toFixed(2);
},
label: function (i, d) {
return (
d.datasets[i.datasetIndex].label + ": " + i.yLabel.toFixed(2)
);
}
}
}
},
data: {
datasets: [
this.generateDataset(0, "A", "red"),
this.generateDataset(1, "B", "green"),
this.generateDataset(2, "C", "blue")
]
}
});
}
drawMyChart() {
this.lineChart = document.getElementById("myChart");
this.ctx = this.lineChart.getContext("2d");
var myChart = new Chart(this.ctx, {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [
this.generateDataset(0, "A", "red"),
this.generateDataset(1, "B", "green")
]
},
options: {
scales: {
xAxes: [{
display: true,
type: 'linear',
position: 'bottom',
id: 'x-axis-0',
ticks: {
source: 'labels'
}
}]
},
tooltips: {
mode: "interpolate",
intersect: false,
callbacks: {
title: function (a, d) {
// return a[0].xLabel.toFixed(2);
return a[0].xLabel;
},
label: function (i, d) {
return (
d.datasets[i.datasetIndex].label + ": " + i.yLabel.toFixed(2)
);
}
}
},
plugins: {
crosshair: {
sync: {
enabled: false
}
}
}
}
});
}
generateDataset(shift, label, color) {
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let data = [];
let index = 0;
while (index < 5) {
data.push({
x: index,
y: getRandomInt(10, 40)
});
index++;
}
var dataset = {
backgroundColor: color,
borderColor: color,
showLine: true,
fill: false,
pointRadius: 2,
label: label,
data: data,
lineTension: 0,
interpolate: true,
xAxisID: 'x-axis-0'
};
return dataset;
}
}
答案 0 :(得分:1)
您需要导入十字准线。
import * as crosshair from 'chartjs-plugin-crosshair';
如果您使用的是ng2-charts,请在ts文件中定义插件。
public chartPlugins = [crosshair];
然后在html页面上使用插件
<canvas baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[plugins]="chartPlugins"
[legend]="barChartLegend"
[chartType]="barChartType"
[colors]="chartColors">
</canvas>