简体   繁体   中英

How to make clickable line in JQuery Flot?

I am using flot to make line charts. One of the functionality I am trying to implement is highting the line (including points on the line and its corresponding legend), if the user clicks on the line, cancel the highlighting if the user clicks anywhere else on the chart.

Tried 'plotclick' event, but it requires clicking on points. I need the ability to get the series when clicking on the line as well.

Hopefully, there is a way to do that.

You have to manually search for the nearest point on the line and then calculate the distance with something like this:

$('#placeholder').on('plotclick', function(event, pos, item) {
    $('#output').empty();
    if (item) { // clicked on point
        $('#output').text('series: ' + item.series.label + ' - datapoint: ' + item.dataIndex);
        return;
    }
    else { // search for line
        for (var i = 1; i < data.length; i++) {
            if (data[i-1][0] <= pos.x && pos.x < data[i][0]) {
                var lineX = (pos.x - data[i-1][0]) / (data[i][0] - data[i-1][0]);
                var lineY = data[i-1][1] + lineX * (data[i][1] - data[i-1][1]);
                if (Math.abs(pos.y - lineY) < maxDistance) {
                    $('#output').html('between datapoints ' + (i-1) + ' and ' + i + '<br />'
                        + 'distance from line: ' + Math.abs(pos.y - lineY).toFixed(3));
                }
                return;
            }
        }
    }
});

See this fiddle for a full example. If you have multiple data series you can search for the nearest point on each line and then calculate the nearest line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM