首页 > 解决方案 > pageX,pageY 到 chartX,chartY 的数据点不协调 highcharts

问题描述

有没有办法将整个页面的 X 和 Y 坐标的坐标转换为图表的点?

我知道你可以反过来。

var manualPt = {pageX:155, pageY: 242} //<--the point I want to display
//on the chart as a datapoint and not a chartX, chartY coordinate.

function onClick(e) {
    $('#report').text('x: ' + e.pageX+ ', y: ' + e.pageY).css({
        'position': 'absolute',
            'left': e.offsetX,
            'top': e.offsetY
    })
   //this would be the reverse.. knowing where the point on the chart is 
   //and then get pageX and pageY
}

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container'
    },
    xAxis: {},
    tooltip: {
        enabled: false
    },
    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        events: {
            click: onClick
        }

    }]
});

http://jsfiddle.net/pinktoadette/yd6vrg4o/

我怎样才能做到这一点?pageX 和 pageY 的坐标也可能不是现有图表中的数据系列。

标签: highcharts

解决方案


您可以计算点相对于图表的像素位置,并使用轴toValue方法获取真实数据:

chart: {
    renderTo: 'container',
    events: {
        load() {
            var chart = this,
                xAxis = chart.xAxis[0],
                yAxis = chart.yAxis[0],
                container = chart.renderTo,
                x = xAxis.toValue(manualPt.pageX - container.offsetLeft),
                y = yAxis.toValue(manualPt.pageY - container.offsetTop);

            this.series[1].addPoint({
                x: x,
                y: y
            });
        }
    }
}

API:https ://api.highcharts.com/class-reference/Highcharts.Axis#toValue

现场演示:http: //jsfiddle.net/BlackLabel/5pytc8mb/


推荐阅读