# ツールチップ

# ツールチップの設定

名前空間: options.plugins.tooltip、チャートツールチップのグローバルオプションはChart.defaults.plugins.tooltipで定義されています。

名前 デフォルト 説明
enabled boolean true キャンバス上のツールチップを有効にしますか?
external function null 外部ツールチップセクションを参照してください。
mode string interaction.mode ツールチップに表示される要素を設定します。詳細...
intersect boolean interaction.intersect trueの場合、ツールチップモードはマウスの位置が要素と交差する場合にのみ適用されます。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 ツールチップ矢印のサイズ(px単位)。
cornerRadius number|object 6 ツールチップの角の曲線の半径。
multiKeyBackground Color '#fff' 複数のアイテムがツールチップにある場合に、カラーボックスの後ろに描画する色。
displayColors boolean true trueの場合、ツールチップにカラーボックスが表示されます。
boxWidth number bodyFont.size displayColorsがtrueの場合のカラーボックスの幅。
boxHeight number bodyFont.size displayColorsがtrueの場合のカラーボックスの高さ。
boxPadding number 1 カラーボックスとテキストの間のパディング。
usePointStyle boolean false カラーボックスの代わりに対応するポイントスタイル(データセットオプションから)を使用します(例:星、三角形など)。(サイズはboxWidthとboxHeightの最小値に基づきます)。
borderColor Color 'rgba(0, 0, 0, 0)' ボーダーの色。
borderWidth number 0 ボーダーのサイズ。
rtl boolean 右から左へのツールチップのレンダリングにはtrue
textDirection string キャンバスのデフォルト キャンバスで指定されたCSSに関係なく、キャンバス上のツールチップをレンダリングするためのテキスト方向'rtl'または'ltr'を強制します。
xAlign string undefined X方向のツールチップキャレットの位置。詳細
yAlign string undefined Y方向のツールチップキャレットの位置。詳細

注記

より多くの視覚的なカスタマイズが必要な場合は、HTMLツールチップを使用してください。

# 位置モード

可能なモードは

  • 'average'
  • 'nearest'

'average'モードは、ツールチップに表示されるアイテムの平均位置にツールチップを配置します。'nearest'は、イベントの位置に最も近い要素の位置にツールチップを配置します。

カスタム位置モードを定義することもできます。

# ツールチップの配置

xAlignおよびyAlignオプションは、ツールチップキャレットの位置を定義します。これらのパラメータが設定されていない場合、最適なキャレット位置が決定されます。

xAlign設定では、次の値がサポートされています。

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

yAlign設定では、次の値がサポートされています。

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

# テキストの配置

titleAlignbodyAlignfooterAlignオプションは、ツールチップボックスに対するテキスト行の水平方向の位置を定義します。次の値がサポートされています。

  • 'left'(デフォルト)
  • 'right'
  • 'center'

これらのオプションはテキスト行のみに適用されます。カラーボックスは常に左端に配置されます。

# ソートコールバック

ツールチップアイテムのソートを許可します。少なくともArray.prototype.sort (新しいウィンドウで開きます)に渡すことができる関数を実装する必要があります。この関数は、チャートに渡されるデータオブジェクトである3番目のパラメータを受け入れることもできます。

# フィルターコールバック

ツールチップアイテムのフィルタリングを許可します。少なくともArray.prototype.filter (新しいウィンドウで開きます)に渡すことができる関数を実装する必要があります。この関数は、チャートに渡されるデータオブジェクトである4番目のパラメータを受け入れることもできます。

# ツールチップコールバック

名前空間: options.plugins.tooltip.callbacks、ツールチップにはテキストを提供するための次のコールバックがあります。すべての関数について、thisTooltipコンストラクタから作成されたツールチップオブジェクトになります。コールバックが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 はい ツールチップ内の個々のアイテムに対してレンダリングされるテキストを返します。詳細...
labelColor TooltipItem object | undefined はい ツールチップアイテムに対してレンダリングされる色を返します。詳細...
labelTextColor TooltipItem Color | undefined はい ツールチップアイテムのラベルテキストの色を返します。
labelPointStyle TooltipItem object | undefined はい usePointStyleがtrueの場合、色のボックスの代わりに使用するポイントスタイルを返します(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コールバックは、特定のデータポイントに表示されるテキストを変更できます。単位を表示する一般的な例です。以下の例では、すべての行の前に'$'を配置します。

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

外部ツールチップの使用方法の例については、サンプルを参照してください。

# ツールチップモデル

ツールチップモデルには、ツールチップのレンダリングに使用できるパラメータが含まれています。

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

より詳細な例については、サンプルを参照してください。

TypeScriptを使用している場合は、新しいモードも登録する必要があります。

declare module 'chart.js' {
  interface TooltipPositionerMap {
    myCustomPositioner: TooltipPositionerFunction<ChartType>;
  }
}
最終更新日: 2024年5月17日 午後12時33分38秒