Skip to content

Invalid witdth cache in line annotation #474

@stockiNail

Description

@stockiNail

In the line annotation, we are calculating the width of the label with a specific function:

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions