# 工具提示

Tooltip

# 工具提示配置

Tooltip Configuration

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

Namespace: options.plugins.tooltip, the global options for the chart tooltips is defined in Chart.defaults.plugins.tooltip.

名称 类型 默认 描述
enabled boolean true 画布上的工具提示是否已启用?
external function null 参见 外部工具提示 部分。
mode string interaction.mode 设置哪些元素出现在工具提示中。更多...
intersect boolean interaction.intersect 如果为真,则工具提示模式仅在鼠标位置与元素相交时适用。如果为 false,则将始终应用该模式。
position string 'average' 定位工具提示的模式。更多...
callbacks object 参见 回调部分
itemSort function 对工具提示项目进行排序。更多...
filter function 过滤工具提示项。更多...
backgroundColor Color 'rgba(0, 0, 0, 0.8)' 工具提示的背景颜色。
titleColor Color '#fff' 标题文本的颜色。
titleFont Font {weight: 'bold'} 字体
titleAlign string 'left' 标题文本行的水平对齐方式。更多...
titleSpacing number 2 添加到每个标题行的顶部和底部的间距。
titleMarginBottom number 6 添加到标题部分底部的边距。
bodyColor Color '#fff' 正文颜色。
bodyFont Font {} 字体
bodyAlign string 'left' 正文文本行的水平对齐方式。更多...
bodySpacing number 2 添加到每个工具提示项的顶部和底部的间距。
footerColor Color '#fff' 页脚文本的颜色。
footerFont Font {weight: 'bold'} 字体
footerAlign string 'left' 页脚文本行的水平对齐方式。更多...
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 工具提示

If you need more visual customizations, please use an HTML tooltip.

# 位置模式

Position Modes

可能的模式是:

Possible modes are:

  • 'average'

  • 'nearest'

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

'average' mode will place the tooltip at the average position of the items displayed in the tooltip. 'nearest' will place the tooltip at the position of the element closest to the event position.

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

You can also define custom position modes.

# 工具提示对齐

Tooltip Alignment

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

The xAlign and yAlign options define the position of the tooltip caret. If these parameters are unset, the optimal caret position is determined.

支持 xAlign 设置的以下值。

The following values for the xAlign setting are supported.

  • 'left'

  • 'center'

  • 'right'

支持 yAlign 设置的以下值。

The following values for the yAlign setting are supported.

  • 'top'

  • 'center'

  • 'bottom'

# 文本对齐

Text Alignment

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

The titleAlign, bodyAlign and footerAlign options define the horizontal position of the text lines with respect to the tooltip box. The following values are supported.

  • 'left'(默认)

    'left' (default)

  • 'right'

  • 'center'

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

These options are only applied to text lines. Color boxes are always aligned to the left edge.

# 排序回调

Sort Callback

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

Allows sorting of tooltip items. Must implement at minimum a function that can be passed to Array.prototype.sort. This function can also accept a third parameter that is the data object passed to the chart.

# 过滤器回调

Filter Callback

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

Allows filtering of tooltip items. Must implement at minimum a function that can be passed to Array.prototype.filter. This function can also accept a fourth parameter that is the data object passed to the chart.

# 工具提示回调

Tooltip Callbacks

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

Namespace: options.plugins.tooltip.callbacks, the tooltip has the following callbacks for providing text. For all functions, this will be the tooltip object created from the Tooltip constructor. If the callback returns undefined, then the default callback will be used. To remove things from the tooltip callback should return an empty string.

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

Namespace: data.datasets[].tooltip.callbacks, items marked with Yes in the column Dataset override can be overridden per dataset.

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

A tooltip item context is generated for each item that appears in the tooltip. This is the primary model that the callback methods interact with. For functions that return text, arrays of strings are treated as multiple lines of text.

名称 参数 返回类型 数据集覆盖 描述
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` 是的 返回要为工具提示中的单个项目渲染的文本。更多...
labelColor TooltipItem `object undefined` 是的 返回要为工具提示项渲染的颜色。更多...
labelTextColor TooltipItem `Color undefined` 是的 返回工具提示项标签文本的颜色。
labelPointStyle TooltipItem `object undefined` 是的 如果 usePointStyle 为真(值为 pointStylerotation 的对象),则返回要使用的点样式而不是颜色框。默认实现使用数据集点中的点样式。更多...
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 Callback

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

The label callback can change the text that displays for a given data point. A common example to show a unit. The example below puts a '$' before every row.

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

# 标签颜色回调

Label Color Callback

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

For example, to return a red box with a blue dashed border that has a border radius for each item in the tooltip you could do:

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

# 标注点样式回调

Label Point Style Callback

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

For example, to draw triangles instead of the regular color box for each item in the tooltip, you could do:

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

# 工具提示项上下文

Tooltip Item Context

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

The tooltip items passed to the tooltip callbacks implement the following interface.

{
    // 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,
}

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

External (Custom) Tooltips

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

External tooltips allow you to hook into the tooltip rendering process so that you can render the tooltip in your own custom way. Generally this is used to create an HTML tooltip instead of an on-canvas tooltip. The external option takes a function which is passed a context parameter containing the chart and tooltip. You can enable external tooltips in the global or chart configuration like so:

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

See samples for examples on how to get started with external tooltips.

# 工具提示模型

Tooltip Model

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

The tooltip model contains parameters that can be used to render the tooltip.

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

# 自定义位置模式

Custom Position Modes

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

New modes can be defined by adding functions to the Chart.Tooltip.positioners map.

示例:

Example:

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

See samples for a more detailed example.

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

If you're using TypeScript, you'll also need to register the new mode:

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