Position tooltip in center of bar

2019-06-12 12:17发布

问题:

Can't find a way to position tooltip in center of bar like this (yeah, I know it is not exactly in center on this screenshot, but still):

If I use custom tooltip option, I can get only x and y positions of a caret on top of a bar. But can't get height/width of a bar.

Here is a part of an options object that I pass to Chart constructor:

const options = {
  tooltips: {
    enabled: false,
    custom: (tooltip) => {
      // Retrieving valuable props from tooltip (caretX, caretY)
      // and creating custom tooltip that is positioned
      // on top of a bar
    }
  }
  // other options
}

const chart = new Chart(ctx, {
  type: 'bar',
  data,
  options
})

回答1:

As you may already know, to position a custom tooltip at the center of a bar, you might need some of it­'s (bar) properties, such as - width, height, top and left position. But unfortunately, there is no straight-forward way of getting these properties, rather you need to calculate them yourself.

To obtain / calculate those properties, you can use the following function (can be named anything), which will return an object containing all these (width, height, top, left) properties of a particular bar, when hovered over.

function getBAR(chart) {
   const dataPoints = tooltipModel.dataPoints,
         datasetIndex = chart.data.datasets.length - 1,
         datasetMeta = chart.getDatasetMeta(datasetIndex),
         scaleBottom = chart.scales['y-axis-0'].bottom,
         bar = datasetMeta.data[dataPoints[0].index]._model,
         canvasPosition = chart.canvas.getBoundingClientRect(),
         paddingLeft = parseFloat(getComputedStyle(chart.canvas).paddingLeft),
         paddingTop = parseFloat(getComputedStyle(chart.canvas).paddingTop),
         scrollLeft = document.body.scrollLeft,
         scrollTop = document.body.scrollTop;

   return {
      top: bar.y + canvasPosition.top + paddingTop + scrollTop,
      left: bar.x - (bar.width / 2) + canvasPosition.left + paddingLeft + scrollLeft,
      width: bar.width,
      height: scaleBottom - bar.y
   }
}

Calculate Center Position

After retrieving the required properties, you can calculate center position of a bar as such :