-
Notifications
You must be signed in to change notification settings - Fork 373
Description
In the line annotation, we are calculating the width of the label with a specific function:
chartjs-plugin-annotation/src/types/line.js
Lines 302 to 327 in 16b68b7
| const widthCache = new Map(); | |
| function measureLabel(ctx, label) { | |
| const content = label.content; | |
| if (content instanceof Image) { | |
| return { | |
| width: getImageSize(content.width, label.width) + 2 * label.xPadding, | |
| height: getImageSize(content.height, label.height) + 2 * label.yPadding | |
| }; | |
| } | |
| const lines = isArray(content) ? content : [content]; | |
| const count = lines.length; | |
| let width = 0; | |
| for (let i = 0; i < count; i++) { | |
| const text = lines[i]; | |
| if (!widthCache.has(text)) { | |
| widthCache.set(text, ctx.measureText(text).width); | |
| } | |
| width = Math.max(width, widthCache.get(text)); | |
| } | |
| width += 2 * label.xPadding; | |
| return { | |
| width, | |
| height: count * label.font.size + ((count + 1) * label.yPadding) | |
| }; | |
| } |
and the result of measure text is cached in a map, with the text of the label as key.
This is logically not correct because the meausement is base on 2 factors: text and font.
That means, if you change the font during the lifecycle of the chart but not the content of the label, the rendering is wrong.
See codepen: https://codepen.io/stockinail/pen/gOxjdGg
After the first draw, clicking on "Change font" button, you can see that the rendering is wrong because the width of the text is not recalculated.
I propose to add the font.string in the key in order to have a consistent logic.
To use the font.string, the line annotation should use toFont function of chartjs helpers and not the toFontString anymore.
Furthermore the line annotation is still using the font.size instead of font.lineHeight and this should be changed as well.
I'm going to submit a PR for that (maybe 2, one for widthCache and one for lineHeight).