Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chart.js filltext object moved when tooltip is generated because of legend not displaying

I wonder if anyone ran into similar situation like this. I am using Chart.js to create a bar chart. One of the requirements for the bar chart component is to display bar data value on the bar itself. I created a simple plugin to do so and it works fine until I notice a display bug.

When hovering over any bars and the tooltip displays, the bar data value got pushed down a bit. I am not sure what happened. It seems that somehow the tooltip adds some sort of space in the chart.

Does anyone ever experience similar behavior?

enter image description here

enter image description here

Below is the plugin created to add the bar data value:

  Chart.pluginService.register({
afterDraw : function (chart ,easingValue, options) {
  var configOptions = chart.config.options;
  if (configOptions.barValueDisplay){
    var ctx = chart.chart.ctx;
    var scales = chart.scales;
    var datasets = chart.config.data.datasets;

    for(var i = 0; i< datasets.length; i++){
      var meta = chart.getDatasetMeta(i);
      var elements = meta.data
      var yScale = scales['y-axis-0'];
      for (var j = 0; j < elements.length; j++) {
        var view = elements[j]._view;

        var text = configOptions.barGoals ? datasets[i].rawData[j] :datasets[i].data[j];
        var textWidth = ctx.measureText(text).width
        var x = view.x - textWidth / 2;
        var y = yScale.bottom-15;
        ctx.save();
        ctx.fillStyle = configOptions.barValueDisplay.color;
        ctx.fillText(text, x, y);
        ctx.restore();
      }
    }
  }
}});

UPDATE: After creating a JSFiddler example, I realize that this behavior is related to legend not displaying.

So, any ideas how this could be addressed without displaying legend? Thanks

https://jsfiddle.net/charleschiu/9fc8n7cb/29/

like image 989
Chuck Avatar asked Oct 22 '25 14:10

Chuck


1 Answers

I was facing the same issue and posted an issue on the repository. Here's the reply:

The reason this is happening is that the tooltip is drawing text using a different textBaseline. The plugin in your fiddle doesn't set it so it will be whatever it last was.

I would change your plugin to have the following

var text = 'test';
var x = view.x;
var y = yScale.bottom;
ctx.textBaseline = 'top';
ctx.textAlign = 'center';
ctx.fillStyle = 'rgba(255, 0, 255, 1)';
ctx.fillText(text, x, y);

I tried it on the Fiddle and it works now!


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!