Skip to content

Commit

Permalink
Skip annotations outside chartArea (chartjs#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
kurkle authored Mar 27, 2021
1 parent 544db3c commit 17bc449
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/annotation.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ function updateElements(chart, state, options, mode) {
}
const opts = resolveAnnotationOptions(annotation.setContext(getContext(chart, el, annotation)));
const properties = el.resolveElementProperties(chart, opts);
properties.skip = isNaN(properties.x) || isNaN(properties.y);
properties.options = opts;
animations.update(el, properties);
}
Expand Down Expand Up @@ -204,7 +205,7 @@ function resyncElements(elements, annotations) {
function draw(chart, caller) {
const {ctx, chartArea} = chart;
const state = chartStates.get(chart);
const elements = state.elements.filter(el => el.options.display);
const elements = state.elements.filter(el => !el.skip && el.options.display);

clipArea(ctx, chartArea);
elements.forEach(el => {
Expand Down
10 changes: 9 additions & 1 deletion src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,17 @@ import {isFinite} from 'chart.js/helpers';
const PI = Math.PI;
const HALF_PI = PI / 2;

function inArea(scale, pixel) {
const area = scale.chart.chartArea;
return scale.isHorizontal()
? pixel >= area.left && pixel <= area.right
: pixel >= area.top && pixel <= area.bottom;
}

export function scaleValue(scale, value, fallback) {
value = typeof value === 'number' ? value : scale.parse(value);
return isFinite(value) ? scale.getPixelForValue(value) : fallback;
value = isFinite(value) ? scale.getPixelForValue(value) : fallback;
return inArea(scale, value) ? value : fallback;
}

/**
Expand Down
40 changes: 40 additions & 0 deletions test/fixtures/line/out-of-range.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
module.exports = {
config: {
type: 'line',
data: {
datasets: [{
data: [10, 20, 30, 0, 55],
}],
labels: ['A', 'B', 'C', 'D', 'E']
},
options: {
scales: {
x: {
min: 'C'
}
},
plugins: {
legend: false,
annotation: {
annotations: {
annotation1: {
type: 'line',
scaleID: 'x',
borderWidth: 3,
borderColor: 'black',
value: 'B',
label: {
backgroundColor: 'red',
content: 'shold not be drawn',
enabled: true
}
}
}
}
},
}
},
options: {
spriteText: true,
}
};
Binary file added test/fixtures/line/out-of-range.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 17bc449

Please sign in to comment.