Chartjs-How do you get the width of a datalabel from the Chartjs plugin after the chart animates?

0๐Ÿ‘

โœ…

You can use the getProps on the model to get the width after the animations are over like so:

offset: function(context) {
  const chart = context.chart;
  const area = chart.chartArea;
  const meta = chart.getDatasetMeta(context.datasetIndex);
  const model = meta.data[context.dataIndex];
  const {
    width
  } = model.getProps(['width'], true);
  console.log(width)
  return 4;
},

Updated codepen: https://codepen.io/leelenaleee/pen/MWQGbdM?editors=1010

0๐Ÿ‘

I might have been thinking about it the wrong way. By playing around with the values I realized the value itself is a pretty good indication of whether it should be inside or outside of the bar. What Iโ€™ve done instead is evaluate if the value is greater than 30. If so the color is white and the anchor is set to start. If it less than 30 the color is black and the anchor is set to end:

https://codepen.io/thoughtassassin/pen/rNJvOrj

plugins: {
    datalabels: {
      color: (context) => getValue(context) > 30 ? '#fff' : '#000',
      anchor: (context) => getValue(context) > 30 ? 'start' : 'end',
      align: 'right',
      offset: 5,
      font: {
        size: 9
      }
    },
  }

Leave a comment