Synchronized HighCharts does not work when charts

2020-05-01 10:43发布

问题:

In HighCharts, I tried with Synchronized multi charts as explained in the Fiddle. It works well if provided all charts have equal width.

$('#container').bind('mousemove touchmove touchstart', function (e) {
    var chart,
        point,
        i,
        event;

    for (i = 0; i < Highcharts.charts.length; i = i + 1) {
        chart = Highcharts.charts[i];
        event = chart.pointer.normalize(e.originalEvent); // Find coordinates within the chart
        point = chart.series[0].searchPoint(event, true); // Get the hovered point

        if (point) {
            point.highlight(e);
        }
    }
});

But If I change the width of the charts to different sizes, then tooltip does not sync properly. You can check this Fiddle.

Is there any way to sync even if charts have different sizes?

回答1:

If you have data with the same x coordinates you can catch the point from the hovered chart and then find the corresponded points in the other two charts - and call highlight().

function highlightPoints(e) {
  const container = this;
  const charts = Highcharts.charts.slice();
  const chartIndex = charts.findIndex(chart => chart.renderTo === container);

  if (chartIndex > -1) {
    const chart = charts.splice(chartIndex, 1)[0];

    const event = chart.pointer.normalize(e.originalEvent); // Find coordinates within the chart
    const point = chart.series[0].searchPoint(event, true); // Get the hovered point

    if (point) {
      const x = point.x;
      point.highlight(e);

      charts.forEach(chart => {
        const points = chart.series[0].points;
        for (let i = 0; i < points.length; i = i + 1) {
          if (points[i].x === x) {
            points[i].highlight(e);
            break;
          }
        }
      })
    }
  }
}

Bind the mousemove event

  $('.chart-0, .chart-1, .chart-2').on('mousemove', highlightPoints);

example: http://jsfiddle.net/5vcc6z40/