ChartJs Data Labels may not fit to vertical or horizontal bars

Viewed 424

I am using chart js v2.9.3 and on that chartjs-plugin-datalabels. My problem is, at display, I call shouldDisplayLabel function in order to decide whether my label will fit inside bar or not.

Chart.defaults.global.plugins.datalabels = {
    color: function (data) {
        return findContrastedColor(data);
    },
    formatter: function(value, context) {
        return value.toFixed(2);
    },
    display: function(ctx) {
        return shouldDisplayLabel(ctx);
    }
}

function doesValueFitToGraph(ctx){
    var value =  ctx.chart.data.datasets[ctx.datasetIndex].data[ctx.dataIndex].toFixed(2);
    var textSize = getTextWidth(value)
    if(ctx.chart.config.type === 'horizontalBar'){
        //todo get bar width
        //I DONT KNOW BAR WIDTH because it is undefined here
        var barHeight = ctx.chart.getDatasetMeta(ctx.datasetIndex).data[ctx.dataIndex]._view.height;
        return (barHeight>13);
    }
    if(ctx.chart.config.type === 'bar'){
        //todo get bar height
        //I DONT KNOW BAR HEIGHT because it is undefined here
        var barWidth = ctx.chart.getDatasetMeta(ctx.datasetIndex).data[ctx.dataIndex]._view.width;
        return (textSize + 2 < barWidth);
    }
    return true;
}

Is there any way that I can get bar height when it is vertical and bar width when it is horizontal? enter image description here enter image description here

Thank you for your time.

0 Answers
Related