Skip to content

Commit

Permalink
Fix nearest interaction mode to return all items
Browse files Browse the repository at this point in the history
Return all items that are at the nearest distance to the point.
Add unit tests for nearest + axis: 'x' and nearest + axis: 'y'
  • Loading branch information
kurkle committed Nov 26, 2018
1 parent b68341d commit b7bb7ed
Show file tree
Hide file tree
Showing 3 changed files with 208 additions and 178 deletions.
2 changes: 1 addition & 1 deletion docs/general/interactions/modes.md
Expand Up @@ -20,7 +20,7 @@ var chart = new Chart(ctx, {
```

## nearest
Gets the item that is nearest to the point. The nearest item is determined based on the distance to the center of the chart item (point, bar). If 2 or more items are at the same distance, the one with the smallest area is used. If `intersect` is true, this is only triggered when the mouse position intersects an item in the graph. This is very useful for combo charts where points are hidden behind bars.
Gets the items that are at the nearest distance to the point. The nearest item is determined based on the distance to the center of the chart item (point, bar). You can use the `axis` setting to define which directions are used in distance calculation. If `intersect` is true, this is only triggered when the mouse position intersects an item in the graph. This is very useful for combo charts where points are hidden behind bars.

```javascript
var chart = new Chart(ctx, {
Expand Down
21 changes: 1 addition & 20 deletions src/core/core.interaction.js
Expand Up @@ -243,26 +243,7 @@ module.exports = {
var position = getRelativePosition(e, chart);
options.axis = options.axis || 'xy';
var distanceMetric = getDistanceMetricForAxis(options.axis);
var nearestItems = getNearestItems(chart, position, options.intersect, distanceMetric);

// We have multiple items at the same distance from the event. Now sort by smallest
if (nearestItems.length > 1) {
nearestItems.sort(function(a, b) {
var sizeA = a.getArea();
var sizeB = b.getArea();
var ret = sizeA - sizeB;

if (ret === 0) {
// if equal sort by dataset index
ret = a._datasetIndex - b._datasetIndex;
}

return ret;
});
}

// Return only 1 item
return nearestItems.slice(0, 1);
return getNearestItems(chart, position, options.intersect, distanceMetric);
},

/**
Expand Down

0 comments on commit b7bb7ed

Please sign in to comment.