Reputation: 137
I am using Chart.js and have been looking for a way to have a Horizontal annotation/crosshair in my graph. This is my code (fiddle):
angular.module("app", ["chart.js"])
.controller("ChartCtrl", function($scope) {
$scope.labels = ["January", "February", "March",
"April", "May", "June", "July"];
$scope.series = ['Series A', 'Series B'];
$scope.data = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
$scope.datasetOverride = [{
yAxisID: 'y-axis-1'
}, {
yAxisID: 'y-axis-2'
}];
$scope.options = {
scales: {
yAxes: [{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
}, {
id: 'y-axis-2',
type: 'linear',
display: true,
position: 'right'
}]
}
};
$scope.labels1 = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
$scope.series1 = ['Series A', 'Series B'];
$scope.data1 = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
});
How to create a horizontal crosshair that changes its position based on the cursor movement using Chart.js?
I have seen that in canvas.js this Functionality works but I want to use chart.js only (canvas.js fiddle).
Upvotes: 1
Views: 1287
Reputation: 4551
Try this:
const options = {
hover: {
intersect: false
},
onHover: function(this: Chart, event: MouseEvent,
activeElements: Array<object>): any {
if (activeElements.length) {
const activePoint = activeElements[0] as any;
const ctx = this.ctx;
if (!ctx) {
return;
}
const x = activePoint._view.x;
const y = activePoint._view.y;
const leftX = this.chartArea.left;
const topY = this.chartArea.top;
const RightX = this.chartArea.right;
const bottomY = this.chartArea.bottom;
ctx.beginPath();
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.moveTo(leftX, y);
ctx.lineTo(RightX, y);
ctx.lineWidth = 1;
ctx.strokeStyle = "#C2C7CC";
ctx.stroke();
ctx.closePath();
}
},
//...
}
Upvotes: 1