# 互動

命名空間:options.interaction,全域互動設定位於 Chart.defaults.interaction。若要設定哪些事件觸發圖表互動,請參閱 事件

名稱 類型 預設值 描述
mode 字串 'nearest' 設定在互動中顯示哪些元素。詳細資訊請參閱 互動模式
intersect 布林值 true 若為 true,則互動模式僅在滑鼠位置與圖表上的項目相交時才適用。
axis 字串 'x' 可以設定為 'x''y''xy''r',以定義在計算距離時使用的方向。'index' 模式的預設值為 'x'dataset'nearest' 模式的預設值為 'xy'
includeInvisible 布林值 布林值 false

若為 true,則在評估互動時,也會包含圖表區域之外的不可見點。

預設情況下,這些選項同時適用於懸停和工具提示互動。相同的選項可以在 options.hover 命名空間中設定,在這種情況下,它們只會影響懸停互動。同樣地,這些選項可以在 options.plugins.tooltip 命名空間中設定,以獨立設定工具提示互動。

# 事件

名稱 類型 預設值 描述
以下屬性定義圖表如何與事件互動。命名空間:options events 字串[] ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']
events 選項定義圖表應該監聽的瀏覽器事件。這些事件中的每一個都會觸發懸停並傳遞給外掛程式。 更多... onHover 函式 null
當任何事件在 chartArea 上觸發時呼叫。傳遞事件、活動元素(長條、點等)的陣列和圖表。 onHover 函式 onClick

當事件類型為 'mouseup''click''contextmenu' 並在 chartArea 上觸發時呼叫。傳遞事件、活動元素的陣列和圖表。

# 事件選項

const chart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    // This chart will not respond to mousemove, etc
    events: ['click']
  }
});

例如,若要讓圖表僅回應點擊事件,您可以執行

const chart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    // All of these (default) events trigger a hover and are passed to all plugins,
    // unless limited at plugin options
    events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
    plugins: {
      tooltip: {
        // Tooltip will only receive click events
        events: ['click']
      }
    }
  }
});

每個外掛程式的事件可以透過在外掛程式選項中定義(允許的)事件陣列來進一步限制

const chart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    // these are the default events:
    // events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
  },
  plugins: [{
    id: 'myEventCatcher',
    beforeEvent(chart, args, pluginOptions) {
      const event = args.event;
      if (event.type === 'mouseout') {
        // process the event
      }
    }
  }]
});

可以使用簡單的外掛程式來捕獲未在 chartArea 上觸發的事件,例如 mouseout

有關外掛程式的更多資訊,請參閱 外掛程式

# 將事件轉換為資料值

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        onClick: (e) => {
            const canvasPosition = Chart.helpers.getRelativePosition(e, chart);
            // Substitute the appropriate scale IDs
            const dataX = chart.scales.x.getValueForPixel(canvasPosition.x);
            const dataY = chart.scales.y.getValueForPixel(canvasPosition.y);
        }
    }
});

常見的情況是取得一個事件(例如點擊),並在圖表上找到事件發生的資料座標。Chart.js 提供了輔助程式,使這個過程變得簡單明瞭。

當使用打包器時,輔助函式必須單獨匯入。有關此內容的完整說明,請前往 整合 頁面

# 模式

當透過 interactionhovertooltips 設定與圖表的互動時,可以使用許多不同的模式。

options.hoveroptions.plugins.tooltipoptions.interaction 延伸而來。因此,如果僅在 options.interaction 中設定 modeintersect 或任何其他通用設定,則懸停和工具提示都會遵守該設定。

以下詳細介紹這些模式以及它們如何與 intersect 設定一起運作。

請參閱 工具提示互動範例,了解不同的模式如何與工具提示一起運作

# point

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        interaction: {
            mode: 'point'
        }
    }
});

尋找與點相交的所有項目。

# nearest

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        interaction: {
            mode: 'nearest'
        }
    }
});

取得距離點最近的項目。最近的項目是根據與圖表項目(點、長條)中心的距離來決定的。您可以使用 axis 設定來定義在距離計算中考慮哪些座標。如果 intersect 為 true,則僅當滑鼠位置與圖表中的項目相交時才會觸發。這對於點隱藏在長條後面的組合圖表非常有用。

# index

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        interaction: {
            mode: 'index'
        }
    }
});

尋找相同索引處的項目。如果 intersect 設定為 true,則使用第一個相交的項目來確定資料中的索引。如果 intersect 為 false,則使用 x 方向上最近的項目來確定索引。

const chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        interaction: {
            mode: 'index',
            axis: 'y'
        }
    }
});

若要在水平長條圖之類的圖表中使用索引模式,其中我們沿著 y 方向搜尋,您可以使用 v2.7.0 中引入的 axis 設定。透過將此值設定為 'y',則會使用 y 方向。

# dataset

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        interaction: {
            mode: 'dataset'
        }
    }
});

尋找相同資料集中的項目。如果 intersect 設定為 true,則使用第一個相交的項目來確定資料中的索引。如果 intersect 為 false,則使用最近的項目來確定索引。

# x

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        interaction: {
            mode: 'x'
        }
    }
});

僅根據位置的 X 座標,傳回所有會相交的項目。適用於垂直游標實作。請注意,這僅適用於笛卡爾圖表。

# y

const chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        interaction: {
            mode: 'y'
        }
    }
});

傳回所有根據位置的 Y 座標相交的項目。適用於水平游標實作。請注意,這僅適用於笛卡爾圖表。

# 自訂互動模式

可以透過將函式新增至 Chart.Interaction.modes 對應來定義新的模式。您可以使用 Chart.Interaction.evaluateInteractionItems 函式來協助實作這些模式。

import { Interaction } from 'chart.js';
import { getRelativePosition } from 'chart.js/helpers';
/**
 * Custom interaction mode
 * @function Interaction.modes.myCustomMode
 * @param {Chart} chart - the chart we are returning items from
 * @param {Event} e - the event we are find things at
 * @param {InteractionOptions} options - options to use
 * @param {boolean} [useFinalPosition] - use final element position (animation target)
 * @return {InteractionItem[]} - items that are found
 */
Interaction.modes.myCustomMode = function(chart, e, options, useFinalPosition) {
  const position = getRelativePosition(e, chart);
  const items = [];
  Interaction.evaluateInteractionItems(chart, 'x', position, (element, datasetIndex, index) => {
    if (element.inXRange(position.x, useFinalPosition) && myCustomLogic(element)) {
      items.push({element, datasetIndex, index});
    }
  });
  return items;
};
// Then, to use it...
new Chart.js(ctx, {
    type: 'line',
    data: data,
    options: {
        interaction: {
            mode: 'myCustomMode'
        }
    }
})

範例

declare module 'chart.js' {
  interface InteractionModeMap {
    myCustomMode: InteractionModeFunction;
  }
}
如果您正在使用 TypeScript,則還需要註冊新模式