score:0

Accepted answer

you can use a plugin to redraw the ticks for you, might need some finetuning for your specific needs:

var options = {
  type: 'line',
  data: {
    labels: [
      ["red", "subtitle"],
      ["blue", "subtitle"],
      ["yellow", "subtitle"],
      ["green", "subtitle"],
      ["purple", "subtitle"],
      ["orange", "subtitle"]
    ],
    datasets: [{
      label: '# of votes',
      data: [12, 19, 3, 5, 2, 3],
      bordercolor: 'red',
      backgroundcolor: 'red'
    }]
  },
  options: {
    plugins: {
      customtextcolor: {
        color: 'blue',
        boxcolor: 'white',
        fontstringsubtitle: 'italic 12px comic sans ms',
        fontstringmain: ''
      }
    }
  },
  plugins: [{
    id: 'customtextcolor',
    afterdraw: (chart, args, opts) => {
      // set all variables needed
      const {
        ctx,
        scales: {
          y,
          x
        }
      } = chart;
      const labelitems = x._labelitems;
      const {
        color,
        boxcolor,
        fontstringmain,
        fontstringsubtitle
      } = opts;
      const defaultfontstring = '12px "helvetica neue", helvetica, arial, sans-serif';

      for (let i = 0; i < labelitems.length; i++) {
        let labelitem = labelitems[i];

        if (!array.isarray(labelitem.label)) {
          continue;
        }

        let metrics = ctx.measuretext(labelitem.label);
        let labelwidth = metrics.width;
        let labelheight = metrics.fontboundingboxascent + metrics.fontboundingboxdescent;

        //draw box over old labels so they are inviseble
        ctx.save();
        ctx.fillstyle = boxcolor || '#ffffff';
        ctx.fillrect((labelitem.translation[0] - labelwidth / 2), labelitem.translation[1], labelwidth, labelheight * labelitem.label.length);
        ctx.restore();

        // draw new text on canvas
        let offset = 0;
        labelitem.label.foreach(el => {
          let eltextmetrics = ctx.measuretext(el);
          let elwidth = eltextmetrics.width;

          if (labelitem.label.indexof(el) === 0) {
            ctx.font = fontstringmain || defaultfontstring;
          } else {
            ctx.font = fontstringsubtitle || defaultfontstring;
          }

          ctx.save();
          ctx.fillstyle = color || chart.defaults.color
          ctx.filltext(el, (labelitem.translation[0] - elwidth / 2), labelitem.translation[1] + labelitem.textoffset + offset);
          ctx.restore();
          offset += eltextmetrics.fontboundingboxascent + eltextmetrics.fontboundingboxdescent;
        });
      }

      // draw white box over old label

    }
  }]
}

var ctx = document.getelementbyid('chartjscontainer').getcontext('2d');
new chart(ctx, options);
<body>
  <canvas id="chartjscontainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/3.5.1/chart.js"></script>
</body>


Related Query

More Query from same tag