Chart.js filltext object is moved when tooltip is being created due to legend not showing

I wonder if anyone has encountered a similar situation. I am using Chart.js to create a bar chart. One of the requirements for the histogram component is to display the bar data value on the panel itself. I created a simple plugin to do this and it works great until I noticed the display error.

When hovering over any columns and tooltips, the data bar value decreased slightly. I'm not sure what happened. It seems that somehow the hint is adding some place to the diagram.

Has anyone encountered similar behavior?

enter image description here

enter image description here

Below is a plugin created to add a 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 the JSFiddler example, I understand that this behavior is due to the legend not being displayed.

So, any ideas how this could be solved without displaying the legend? Thanks to

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

+3


source to share


1 answer


I faced the same problem and posted the issue to the repository. Here's the answer:

The reason this is happening is because the tooltip is drawing text using a different textBaseline. The plugin in your fiddle doesn't install it so this will be the last one.

I would modify 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 this on a violin and now it works!

+4


source







All Articles