首页 > 解决方案 > Chart.js 重叠工具提示文本

问题描述

我有一个 chart.js 折线图:

var myLineChart = new Chart(ctx, {
                type: 'line',
                data: lineChartData,
                options: {
                    tooltips: {
                        titleSpacing: 5,
                    },
                    responsive: true,
                    legend: {
                        display: false,
                    },
                    scales: {
                        yAxes: \[
                            {
                                gridLines: {
                                    color: '#354657',
                                },
                                ticks: {
                                    fontColor: '#fff',
                                    stepSize: 5,
                                },
                            },
                        \],
                        xAxes: \[
                            {
                                gridLines: {
                                    color: '#354657',
                                },
                                ticks: {
                                    fontColor: '#fff',
                                },
                            },
                        \],
                    },
                },]

问题是,它呈现带有重叠文本的工具提示,如下所示: 1]

这应该显示 Current, 41.9。但它们是重叠的。我尝试改变titlespacing,但这并没有做任何事情。我怎样才能解决这个问题?

标签: javascriptchart.js

解决方案


我个人对所有自定义图表所做的是创建一个自定义标题/标签,独立于我作为选项传递给图表的内容。我喜欢控制 HTML / 输出到标签的任何内容。您可以使用回调键执行此操作

  tooltips: {
    enabled: true,
    position: "nearest",
    caretSize: 20,
    mode: "index",
    intersect: false,
    titleFontSize: 16,
    titleFontColor: "white",
    backgroundColor: COLORS.DARK,
    callbacks: {
      title: (tooltipItem, _) => {
        return formatDate("LT", tooltipItem[0].xLabel);
      },
      label: (tooltipItem, _) => {
        const { yLabel } = tooltipItem;
        return `${yLabel} Sessions Recorded`;
      }
    }
  },

推荐阅读