问题描述
给定一个现有的 Highcharts(在一个使用 highcharts-react-official
的 React 组件中),我们怎样才能让它当用户点击图表上的 2 个点时,这 2 个点之间的值的差异将被计算并显示在图表中的文本框中?
为了说明所需的结果,下面的图像显示了一个绿色文本框,在用户单击折线图上的 2 个点后,值的百分比差异。
我们如何使用 Highcharts 实现这一目标?
解决方法
该功能不需要任何反应逻辑。您只需要对一个点使用 click
回调函数和 addAnnotations
方法。示例:
point: {
events: {
click: function() {
const point = this;
const chart = point.series.chart;
const previousPoint = chart.clickedPoint;
if (previousPoint) {
chart.clickedPoint = null;
chart.addAnnotation({
shapes: [{
type: 'path',strokeWidth: 1,stroke: 'red',dashStyle: 'dash',points: [{
x: point.x,y: point.y,xAxis: 0,yAxis: 0
},{
x: previousPoint.x,y: previousPoint.y,yAxis: 0
}]
}],labels: [{
allowOverlap: true,format: 100 - (previousPoint.y * 100 / point.y) + '%',shape: 'rect',point: {
x: (point.x < previousPoint.x ? point.x : previousPoint.x) +
Math.abs(point.x - previousPoint.x) / 2,y: (point.y < previousPoint.y ? point.y : previousPoint.y) +
Math.abs(point.y - previousPoint.y) / 2,yAxis: 0
}
}]
});
} else {
chart.clickedPoint = this;
}
}
}
}
现场演示: http://jsfiddle.net/BlackLabel/gzcrp0x4/
API 参考: https://api.highcharts.com/class-reference/Highcharts.Chart#addAnnotation