Synchronizing Axis Crosshair across Multiple Charts in a Page | CanvasJS JavaScript Charts
Synchronizing Axis Crosshair across Multiple Charts in a Page | CanvasJS JavaScript Charts
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<center><h3>Move Mouse Over any Chart</h3></center>
<div id="chartContainer1" style="width: 49%; height: 275px;display: inline-block;"></div>
<div id="chartContainer2" style="width: 49%; height: 275px;display: inline-block;"></div>
<span id="xValue1"></span>
JavaScript
var charts = [],
axisX = {
crosshair: {
enabled: true,
updated: showCrosshair,
hidden: hideCrosshair
}
};
var chart1 = new CanvasJS.Chart("chartContainer1", {
title: {
text: "Chart 1"
},
animationEnabled: true,
backgroundColor: "black",
theme: "dark2", // "light1", "light2", "dark1", "dark2"
toolTip: {
updated: function(e) {
document.getElementById("xValue1").innerText= ("Current Tooltip X-Value: " + CanvasJS.formatNumber(e.entries[0].xValue, "##.##") + " | ");
}
},
axisX: axisX,
data: [{
type: "line",
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 }
]
}]
});
chart1.render();
charts.push(chart1);
var chart2 = new CanvasJS.Chart("chartContainer2", {
title: {
text: "Chart 2"
}, toolTip: {
updated: function(e) {
document.getElementById("xValue2").innerText= ("Current Tooltip X-Value: " + CanvasJS.formatNumber(e.entries[0].value, "##.##") + " | " + CanvasJS.formatNumber(e.entries[0].value, "##.##"));
}
},
axisX: axisX,
data: [{
type: "line",
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 }
]
}]
});
chart2.render();
charts.push(chart2);
function showCrosshair(e) {
for( var i = 0; i < charts.length; i++){
if(charts[i] != e.chart)
charts[i].axisX[0].crosshair.showAt(e.value);
}
}
function hideCrosshair(e) {
for( var i = 0; i < charts.length; i++){
if(charts[i] != e.chart)
charts[i].axisX[0].crosshair.hide();
}
}