Replies: 4 comments 1 reply
-
@Camology wrapping text is not implemented. But let me take time if I can find a workaround. |
Beta Was this translation helpful? Give feedback.
-
@Camology I have created a codepen as workaround. It could be improved a bit, but it should work. https://codepen.io/stockinail/pen/wvYMPyY I'm setting the content of the label by a scriptable options as following: annotation: {
annotations: {
box: {
type: 'box',
xMin: 1,
xMax: 2,
backgroundColor: 'rgba(0,0,0,0.3)',
label: {
display: true,
content: (ctx) => wrappingText(ctx, 'This is my text and is very long but it could be more longest')
}
}
}
} Here is the wrapping text function (can be really improved): const wrappingText = function({id, chart}, text) {
const {ctx, scales, options} = chart;
const xScale = scales.x;
const annOptions = options.plugins.annotation.annotations[id];
const left = xScale.getPixelForValue(annOptions.xMin);
const right = xScale.getPixelForValue(annOptions.xMax);
const maxWidth = right - left;
const font = Chart.helpers.toFont(annOptions.label.font);
ctx.save();
ctx.font = font.string;
const width = ctx.measureText(text).width;
ctx.restore();
if (maxWidth < width) {
const result = [];
const len = text.length;
const div = Math.trunc(width / maxWidth);
const trunk = len / (div + 1);
const words = text.split(' ');
let temp = '';
for (const w of words) {
if ((temp.length + w.length) <= trunk) {
temp += w + ' ';
} else {
result.push(temp);
temp = w + ' ';
}
}
if (temp.length) {
result.push(temp);
}
return result;
}
return text;
} |
Beta Was this translation helpful? Give feedback.
-
@Camology I don't know if what I have proposed you it's working for you as well. Anyway, I have submitted an issue (enhancement) to check if this could be provided ootb. |
Beta Was this translation helpful? Give feedback.
-
appreciate the followup, haven't had a time to test due to shifting priorities but will update this story once I do. |
Beta Was this translation helpful? Give feedback.
-
Tried to search for others with a similar issue but did not find one, apologies if there is one out there already just point me towards it please.
Basically the goal here is to have my text wrap when used as a label for a box annotation, currently you can split by using the content array which is fine if you have set boundaries, however I have variable width boxes that will be placed when needed for example:
When the caution block covers a few spots on the X axis it's fine, but it can theoretically cover just 1 place or all of them, is there a way to adjust the label such that it will wrap text at the edges? I tried using inline SVGs but nothing seemed to function properly.
Beta Was this translation helpful? Give feedback.
All reactions