Skip to content

Commit b1880db

Browse files
Add crosshair plugin to enhance chart interactivity
1 parent a54b823 commit b1880db

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

src/crosshair.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
let currentX = null;
2+
const charts = [];
3+
4+
const crosshairPlugin = {
5+
id: 'crosshair',
6+
afterInit(chart) {
7+
charts.push(chart);
8+
9+
chart.canvas.addEventListener('mousemove', (e) => {
10+
const rect = chart.canvas.getBoundingClientRect();
11+
const mouseX = e.clientX - rect.left;
12+
currentX = chart.scales.x.getValueForPixel(mouseX);
13+
charts.forEach(c => c.update('none'));
14+
});
15+
16+
chart.canvas.addEventListener('mouseleave', () => {
17+
currentX = null;
18+
charts.forEach(c => c.update('none'));
19+
});
20+
},
21+
22+
afterDraw(chart) {
23+
if (currentX === null) return;
24+
const xPixel = chart.scales.x.getPixelForValue(currentX);
25+
const { ctx, scales: { y } } = chart;
26+
27+
ctx.save();
28+
ctx.beginPath();
29+
ctx.moveTo(xPixel, y.top);
30+
ctx.lineTo(xPixel, y.bottom);
31+
ctx.lineWidth = 1;
32+
ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
33+
ctx.setLineDash([4, 4]);
34+
ctx.stroke();
35+
ctx.restore();
36+
},
37+
38+
beforeDestroy(chart) {
39+
const index = charts.indexOf(chart);
40+
if (index > -1) charts.splice(index, 1);
41+
}
42+
};
43+
44+
module.exports = crosshairPlugin;

src/setup.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ const Scenario = require("./scenario");
99
const LineChart = require("./charts");
1010
const Cfd = require("./CumulativeFlowDiagram");
1111
const {parseInput} = require("./parsing");
12+
const { Chart } = require('chart.js');
13+
const crosshairPlugin = require('./crosshair');
14+
Chart.register(crosshairPlugin);
1215

1316
// force repeatable randomness
1417
const seedrandom = require('seedrandom');

0 commit comments

Comments
 (0)