# 工具提示

# 工具提示配置

命名空间: options.plugins.tooltip,图表工具提示的全局选项在 Chart.defaults.plugins.tooltip 中定义。

名称 类型 默认 描述
enabled boolean true 画布上的工具提示是否已启用?
external function null 参见 外部工具提示 部分。
mode string interaction.mode 设置哪些元素出现在工具提示中。 more....
intersect boolean interaction.intersect 如果为真,则工具提示模式仅在鼠标位置与元素相交时适用。 如果为 false,则将始终应用该模式。
position string 'average' 定位工具提示的模式。 more...
callbacks object 参见 回调部分
itemSort function 对工具提示项目进行排序。 more...
filter function 过滤工具提示项。 more...
backgroundColor Color 'rgba(0, 0, 0, 0.8)' 工具提示的背景颜色。
titleColor Color '#fff' 标题文本的颜色。
titleFont Font {weight: 'bold'} 字体
titleAlign string 'left' 标题文本行的水平对齐方式。 more...
titleSpacing number 2 添加到每个标题行的顶部和底部的间距。
titleMarginBottom number 6 添加到标题部分底部的边距。
bodyColor Color '#fff' 正文颜色。
bodyFont Font {} 字体
bodyAlign string 'left' 正文文本行的水平对齐方式。 more...
bodySpacing number 2 添加到每个工具提示项的顶部和底部的间距。
footerColor Color '#fff' 页脚文本的颜色。
footerFont Font {weight: 'bold'} 字体
footerAlign string 'left' 页脚文本行的水平对齐方式。 more...
footerSpacing number 2 添加到每个页脚行的顶部和底部的间距。
footerMarginTop number 6 在绘制页脚之前添加的边距。
padding Padding 6 工具提示内的填充。
caretPadding number 2 将工具提示箭头的末端从工具提示点移开的额外距离。
caretSize number 5 工具提示箭头的大小(以像素为单位)。
cornerRadius number|object 6 工具提示角曲线的半径。
multiKeyBackground Color '#fff' 当工具提示中有多个项目时,在彩色框后面绘制的颜色。
displayColors boolean true 如果为 true,工具提示中将显示颜色框。
boxWidth number bodyFont.size 如果 displayColors 为真,则颜色框的宽度。
boxHeight number bodyFont.size 如果 displayColors 为真,则颜色框的高度。
boxPadding number 1 颜色框和文本之间的填充。
usePointStyle boolean false 使用相应的点样式(来自数据集选项)而不是颜色框,例如: 星形、三角形等(大小基于 boxWidth 和 boxHeight 之间的最小值)。
borderColor Color 'rgba(0, 0, 0, 0)' 边框的颜色。
borderWidth number 0 边框的大小。
rtl boolean true 用于从右到左渲染工具提示。
textDirection string 画布的默认值 这将强制画布上的文本方向 'rtl''ltr' 以渲染工具提示,而不管画布上指定的 css
xAlign string undefined 工具提示插入符号在 X 方向上的位置。 more
yAlign string undefined 工具提示插入符号在 Y 方向上的位置。 more

注意

如果你需要更多视觉定制,请使用 HTML 工具提示

# 位置模式

可能的模式是:

  • 'average'
  • 'nearest'

'average' 模式会将工具提示放置在工具提示中显示的项目的平均位置。 'nearest' 会将工具提示放置在最接近事件位置的元素位置。

你还可以定义 自定义位置模式

# 工具提示对齐

xAlignyAlign 选项定义工具提示插入符号的位置。 如果未设置这些参数,则会确定最佳插入符位置。

支持 xAlign 设置的以下值。

  • 'left'
  • 'center'
  • 'right'

支持 yAlign 设置的以下值。

  • 'top'
  • 'center'
  • 'bottom'

# 文本对齐

titleAlignbodyAlignfooterAlign 选项定义文本行相对于工具提示框的水平位置。 支持以下值。

  • 'left' (默认)
  • 'right'
  • 'center'

这些选项仅适用于文本行。 颜色框始终与左边缘对齐。

# 排序回调

允许对 工具提示项 进行排序。 必须至少实现一个可以传递给 Array.prototype.sort (opens new window) 的函数。 此函数还可以接受第三个参数,即传递给图表的数据对象。

# 过滤器回调

允许过滤 工具提示项。 必须至少实现一个可以传递给 Array.prototype.filter (opens new window) 的函数。 此函数还可以接受第四个参数,即传递给图表的数据对象。

# 工具提示回调

命名空间: options.plugins.tooltip.callbacks,工具提示具有以下用于提供文本的回调。 对于所有函数,this 将是从 Tooltip 构造函数创建的工具提示对象。 如果回调返回 undefined,则将使用默认回调。 要从工具提示回调中删除内容,应返回一个空字符串。

命名空间: data.datasets[].tooltip.callbacksDataset override 列中标有 Yes 的项目可以按数据集覆盖。

为工具提示中出现的每个项目生成一个 工具提示项上下文。 这是回调方法与之交互的主要模型。 对于返回文本的函数,字符串数组被视为多行文本。

名称 参数 返回类型 数据集覆盖 描述
beforeTitle TooltipItem[] string | string[] | undefined 返回要在标题之前渲染的文本。
title TooltipItem[] string | string[] | undefined 返回要渲染为工具提示标题的文本。
afterTitle TooltipItem[] string | string[] | undefined 返回要在标题后渲染的文本。
beforeBody TooltipItem[] string | string[] | undefined 返回要在正文部分之前渲染的文本。
beforeLabel TooltipItem string | string[] | undefined 是的 返回要在单个标签之前渲染的文本。 这将为工具提示中的每个项目调用。
label TooltipItem string | string[] | undefined 是的 返回要为工具提示中的单个项目渲染的文本。 more...
labelColor TooltipItem object | undefined 是的 返回要为工具提示项渲染的颜色。 more...
labelTextColor TooltipItem Color | undefined 是的 返回工具提示项标签文本的颜色。
labelPointStyle TooltipItem object | undefined 是的 如果 usePointStyle 为真(值为 pointStylerotation 的对象),则返回要使用的点样式而不是颜色框。 默认实现使用数据集点中的点样式。 more...
afterLabel TooltipItem string | string[] | undefined 是的 返回要在单个标签后渲染的文本。
afterBody TooltipItem[] string | string[] | undefined 返回要在正文部分之后渲染的文本。
beforeFooter TooltipItem[] string | string[] | undefined 返回要在页脚部分之前渲染的文本。
footer TooltipItem[] string | string[] | undefined 返回要渲染为工具提示页脚的文本。
afterFooter TooltipItem[] string | string[] | undefined 在页脚部分之后渲染的文本。

# 标签回调

label 回调可以更改为给定数据点显示的文本。 显示单位的常见示例。 下面的示例在每一行之前放置一个 '

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        plugins: {
            tooltip: {
                callbacks: {
                    label: function(context) {
                        let label = context.dataset.label || '';
                        if (label) {
                            label += ': ';
                        }
                        if (context.parsed.y !== null) {
                            label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(context.parsed.y);
                        }
                        return label;
                    }
                }
            }
        }
    }
});

# 标签颜色回调

例如,要返回一个带有蓝色虚线边框的红色框,工具提示中的每个项目都有一个边框半径,你可以这样做:

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        plugins: {
            tooltip: {
                callbacks: {
                    labelColor: function(context) {
                        return {
                            borderColor: 'rgb(0, 0, 255)',
                            backgroundColor: 'rgb(255, 0, 0)',
                            borderWidth: 2,
                            borderDash: [2, 2],
                            borderRadius: 2,
                        };
                    },
                    labelTextColor: function(context) {
                        return '#543453';
                    }
                }
            }
        }
    }
});

# 标注点样式回调

例如,要为工具提示中的每个项目绘制三角形而不是常规颜色框,你可以执行以下操作:

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        plugins: {
            tooltip: {
                usePointStyle: true,
                callbacks: {
                    labelPointStyle: function(context) {
                        return {
                            pointStyle: 'triangle',
                            rotation: 0
                        };
                    }
                }
            }
        }
    }
});

# 工具提示项上下文

传递给工具提示回调的工具提示项实现以下接口。

{
    // The chart the tooltip is being shown on
    chart: Chart
    // Label for the tooltip
    label: string,
    // Parsed data values for the given `dataIndex` and `datasetIndex`
    parsed: object,
    // Raw data values for the given `dataIndex` and `datasetIndex`
    raw: object,
    // Formatted value for the tooltip
    formattedValue: string,
    // The dataset the item comes from
    dataset: object
    // Index of the dataset the item comes from
    datasetIndex: number,
    // Index of this data item in the dataset
    dataIndex: number,
    // The chart element (point, arc, bar, etc.) for this tooltip item
    element: Element,
}

# 外部(自定义)工具提示

外部工具提示允许你挂接到工具提示渲染过程,以便你可以以自己的自定义方式渲染工具提示。 通常这用于创建 HTML 工具提示而不是画布上的工具提示。 external 选项接受一个函数,该函数传递一个包含 charttooltip 的上下文参数。 你可以像这样在全局或图表配置中启用外部工具提示:

const myPieChart = new Chart(ctx, {
    type: 'pie',
    data: data,
    options: {
        plugins: {
            tooltip: {
                // Disable the on-canvas tooltip
                enabled: false,
                external: function(context) {
                    // Tooltip Element
                    let tooltipEl = document.getElementById('chartjs-tooltip');
                    // Create element on first render
                    if (!tooltipEl) {
                        tooltipEl = document.createElement('div');
                        tooltipEl.id = 'chartjs-tooltip';
                        tooltipEl.innerHTML = '<table></table>';
                        document.body.appendChild(tooltipEl);
                    }
                    // Hide if no tooltip
                    const tooltipModel = context.tooltip;
                    if (tooltipModel.opacity === 0) {
                        tooltipEl.style.opacity = 0;
                        return;
                    }
                    // Set caret Position
                    tooltipEl.classList.remove('above', 'below', 'no-transform');
                    if (tooltipModel.yAlign) {
                        tooltipEl.classList.add(tooltipModel.yAlign);
                    } else {
                        tooltipEl.classList.add('no-transform');
                    }
                    function getBody(bodyItem) {
                        return bodyItem.lines;
                    }
                    // Set Text
                    if (tooltipModel.body) {
                        const titleLines = tooltipModel.title || [];
                        const bodyLines = tooltipModel.body.map(getBody);
                        let innerHtml = '<thead>';
                        titleLines.forEach(function(title) {
                            innerHtml += '<tr><th>' + title + '</th></tr>';
                        });
                        innerHtml += '</thead><tbody>';
                        bodyLines.forEach(function(body, i) {
                            const colors = tooltipModel.labelColors[i];
                            let style = 'background:' + colors.backgroundColor;
                            style += '; border-color:' + colors.borderColor;
                            style += '; border-width: 2px';
                            const span = '<span style="' + style + '">' + body + '</span>';
                            innerHtml += '<tr><td>' + span + '</td></tr>';
                        });
                        innerHtml += '</tbody>';
                        let tableRoot = tooltipEl.querySelector('table');
                        tableRoot.innerHTML = innerHtml;
                    }
                    const position = context.chart.canvas.getBoundingClientRect();
                    const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);
                    // Display, position, and set styles for font
                    tooltipEl.style.opacity = 1;
                    tooltipEl.style.position = 'absolute';
                    tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
                    tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
                    tooltipEl.style.font = bodyFont.string;
                    tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
                    tooltipEl.style.pointerEvents = 'none';
                }
            }
        }
    }
});

有关如何开始使用外部工具提示的示例,请参阅 samples

# 工具提示模型

工具提示模型包含可用于渲染工具提示的参数。

{
    chart: Chart,
    // The items that we are rendering in the tooltip. See Tooltip Item Interface section
    dataPoints: TooltipItem[],
    // Positioning
    xAlign: string,
    yAlign: string,
    // X and Y properties are the top left of the tooltip
    x: number,
    y: number,
    width: number,
    height: number,
    // Where the tooltip points to
    caretX: number,
    caretY: number,
    // Body
    // The body lines that need to be rendered
    // Each object contains 3 parameters
    // before: string[] // lines of text before the line with the color square
    // lines: string[], // lines of text to render as the main item with color square
    // after: string[], // lines of text to render after the main lines
    body: object[],
    // lines of text that appear after the title but before the body
    beforeBody: string[],
    // line of text that appear after the body and before the footer
    afterBody: string[],
    // Title
    // lines of text that form the title
    title: string[],
    // Footer
    // lines of text that form the footer
    footer: string[],
    // style to render for each item in body[]. This is the style of the squares in the tooltip
    labelColors: TooltipLabelStyle[],
    labelTextColors: Color[],
    labelPointStyles: { pointStyle: PointStyle; rotation: number }[],
    // 0 opacity is a hidden tooltip
    opacity: number,
    // tooltip options
    options: Object
}

# 自定义位置模式

可以通过向 Chart.Tooltip.positioners 映射添加功能来定义新模式。

例子:

import { Tooltip } from 'chart.js';
/**
 * Custom positioner
 * @function Tooltip.positioners.myCustomPositioner
 * @param elements {Chart.Element[]} the tooltip elements
 * @param eventPosition {Point} the position of the event in canvas coordinates
 * @returns {TooltipPosition} the tooltip position
 */
Tooltip.positioners.myCustomPositioner = function(elements, eventPosition) {
    // A reference to the tooltip model
    const tooltip = this;
    /* ... */
    return {
        x: 0,
        y: 0
        // You may also include xAlign and yAlign to override those tooltip options.
    };
};
// Then, to use it...
new Chart.js(ctx, {
    data,
    options: {
        plugins: {
            tooltip: {
                position: 'myCustomPositioner'
            }
        }
    }
})

有关更详细的示例,请参见 samples

如果你使用的是 TypeScript,你还需要注册新模式:

declare module 'chart.js' {
  interface TooltipPositionerMap {
    myCustomPositioner: TooltipPositionerFunction<ChartType>;
  }
}