StackFish
StackFish

Reputation: 43

HighCharts draw custom line segment annotation

Current highcharts support free drawing of a line segment annotation. But I want to be able to draw a line based on the data points on the chart series. Basically I want to implement:

  1. click on first point in the chart series to select the first data point
  2. click on the second point on the chart to select the second data point
  3. draw a line segment with those two data points
  4. I should be able to edit the segment just like current highcharts annotations. The edit dialog should show line segment option plus two data points which I can edit.

Any idea how to implement this?

Upvotes: 0

Views: 945

Answers (1)

Sebastian Wędzel
Sebastian Wędzel

Reputation: 11633

Let's start with this demo: https://jsfiddle.net/BlackLabel/7xvr85wt/

Select two points by clicking on them & holding the shift, next click on the button. Is that an output that you want to achieve? Now, what do you want to add to this segment line?

const chart = Highcharts.chart('container', {

  series: [{
    data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175],
    allowPointSelect: true,
  }]
});

function drawPath(points) {
  points.length = 2;
  const x1 = points[0].plotX + chart.plotLeft,
    x2 = points[1].plotX + chart.plotLeft,
    y1 = points[0].plotY + chart.plotTop,
    y2 = points[1].plotY + chart.plotTop;

  chart.renderer.path(['M', x1, y1, 'L', x2, y2])
    .attr({
      'stroke-width': 2,
      stroke: 'red'
    })
    .add();
}

const btn = document.getElementById('btn');

btn.addEventListener('click', function() {
  const selectedPoints = [];
  chart.series[0].points.forEach(p => {
    if (p.selected) {
      selectedPoints.push(p);
    }
  })

  drawPath(selectedPoints);
});

API: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#path

Upvotes: 1

Related Questions