[Chartjs]-Treemap chart.js text wrap

0👍

I solved it by splitting the text into multiple lines, starting a new line whenever the max width would be exceeded.

const chart = new Chart(context, {
    type: 'treemap',
      data:  {
        datasets: [
          {
/* ... */
            labels: {
              display: true,
              formatter(ctx: TreemapScriptableContext) {
                if (ctx.type !== 'data') {
                  return;
                }
                return splitLabelToFit(ctx.raw["_data"].label, ctx.raw.w*0.9, ctx);
              }
            }
          }
        ],
      },
    });

function splitLabelToFit(label: string, maxWidth: number, ctx: TreemapScriptableContext) {
    const words = label.split(' ');
    const lines = [];
    let currentLine = '';
    for (let i = 0; i < words.length; i++) {
      const word = words[i];
      const newLine = currentLine + ' ' + word;
      const width = ctx.chart.ctx.measureText(newLine).width;
      if (width < maxWidth) {
        currentLine = newLine;
      } else {
        lines.push(currentLine);
        currentLine = word;
      }
    }
    lines.push(currentLine);
    return lines;
  }

Leave a comment