0

I'm trying to position a custom Chart.js tooltip on the middle of two bars. I made a research on the chart.js docs and different posts but didn't found any different approach than position it using the following snippet (I'm using jquery and doing a toggle class to hide/show the tooltip, please focus on the values I'm using to position the tooltip):

function setupTooltipPosition(config) {
  const { tooltipElement, tooltipModel } = config;
  const leftOffset = this._chart.canvas.offsetLeft;
  const topOffset = this._chart.canvas.offsetTop;

  tooltipElement.removeClass(tooltipSelectors.hide);
  tooltipElement.css('left', `${tooltipModel.caretX - leftOffset}px`);
  tooltipElement.css('top', `${tooltipModel.carteY - topOffset}px`);
}

Using this approach on this particular case I got this result:

[Tooltip positioned using default implementation]

I also tried using the x and y values of the tooltipModel , however , it doesn't add more sense of how to put the tooltip in the middle. If you tried to add a custom offset to put it on the middle , it works for just this case, but when you add more data it doesn't work. I can have at most 2 datasets, however, the user can add at most 10 data values that means 10 groups of bars.

The question is: There is a way to put the tooltip in the middle of the group of bars (or a single bar in case the user has just 1 dataset) using the values that Chart.js provide for tooltips? Or in other case, do you know any custom approach to have this tooltip centered?

Thanks!!

4

1 回答 1

0

您没有指定“中间”是否在 x 轴和/或 y 轴上。但既然你写了:

...在两个酒吧的中间...

我假设您的意思是在 x 轴上。在这种情况下,您需要将options.tooltips.mode属性设置为index. 下面是一个工作示例。

let myChart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: ['x', 'y', 'z'],
    datasets: [{
      label: '1993',
      data: [50, 30, 65],
      backgroundColor: '#503291'
    }, {
      label: '1994',
      data: [60, 15, 65],
      backgroundColor: '#1bbecd'
    }]
  },
  options: {
    tooltips: {
      mode: 'index'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        barPercentage: 1
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>

对于未来的问题,请提供MCVE,因为这样可以更快、更轻松地为您提供帮助。

于 2018-10-11T10:39:36.733 回答