愿所有的美好和期待都能如约而至

将工具提示放置在栏的中心

发布时间:  来源:互联网  作者:匿名  标签:chart.js charts error Position tooltip in center of bar exception IT资讯 javascrip  热度:37.5℃

本文介绍了将工具提示放置在栏的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到像这样将工具提示放置在栏中心的方法(是的,我知道它不完全在此屏幕截图的中心,但仍然):

如果我使用custom工具提示选项,我只能获得插入符号在栏顶部的xy位置。但无法获取条的高度/宽度。

下面是我传递给图表构造函数的Options对象的一部分:

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
})

推荐答案

您可能已经知道,要将自定义工具提示放置在栏的中心,您可能需要它的一些(栏)属性,例如-宽度、高度、顶部和左侧位置。但不幸的是,没有直接的方法来获取这些属性,而是需要您自己计算它们。

若要获取/计算这些属性,您可以使用以下函数(可以任意命名),该函数将返回一个对象,该对象包含特定条形图的所有这些(宽度、高度、顶部、左侧)属性。

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
   }
}

计算居中位置

检索所需属性后,您可以计算条形的中心位置,如下所示:

勇敢去编程!

勇敢的热爱编程,未来的你一定会大放异彩,未来的生活一定会因编程更好!

TOP