# API

对于每个图表,共享图表类型上都有一组全局原型方法,你可能会发现它们很有用。这些在使用 Chart.js 创建的所有图表上都可用,但对于示例,让我们使用我们制作的折线图。

¥For each chart, there are a set of global prototype methods on the shared chart type which you may find useful. These are available on all charts created with Chart.js, but for the examples, let's use a line chart we've made.

// For example:
const myLineChart = new Chart(ctx, config);

# .destroy()

使用它来销毁创建的任何图表实例。这将清除存储在 Chart.js 中的图表对象的任何引用,以及 Chart.js 附加的任何关联事件监听器。这必须在画布重新用于新图表之前调用。

¥Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js. This must be called before the canvas is reused for a new chart.

// Destroys a specific chart instance
myLineChart.destroy();

# .update(mode?)

触发图表的更新。这可以在更新数据对象后安全地调用。这将更新所有比例、图例,然后重新渲染图表。

¥Triggers an update of the chart. This can be safely called after updating the data object. This will update all scales, legends, and then re-render the chart.

myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.

可以提供 mode 字符串以指示应使用转换配置。核心使用 'active''hide''reset''resize''show'undefined 中的任何一个调用此方法。'none' 也是一种支持跳过单个更新动画的模式。有关详细信息,请参阅 animations 文档。

¥A mode string can be provided to indicate transition configuration should be used. Core calls this method using any of 'active', 'hide', 'reset', 'resize', 'show' or undefined. 'none' is also a supported mode for skipping animations for single update. Please see animations docs for more details.

示例:

¥Example:

myChart.update('active');

有关详细信息,请参阅 更新图表

¥See Updating Charts for more details.

# .reset()

将图表重置为初始动画之前的状态。然后可以使用 update 触发新动画。

¥Reset the chart to its state before the initial animation. A new animation can then be triggered using update.

myLineChart.reset();

# .render()

触发所有图表元素的重绘。请注意,这不会更新新数据的元素。在这种情况下使用 .update()

¥Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use .update() in that case.

# .stop()

使用它来停止任何当前动画。这将在任何当前动画帧期间暂停图表。调用 .render() 重新设置动画。

¥Use this to stop any current animation. This will pause the chart during any current animation frame. Call .render() to re-animate.

// Stops the charts animation loop at its current frame
myLineChart.stop();
// => returns 'this' for chainability

# .resize(width?, height?)

使用它来手动调整画布元素的大小。每次调整画布容器大小时都会运行此方法,但如果更改画布节点容器元素的大小,则可以手动调用此方法。

¥Use this to manually resize the canvas element. This is run each time the canvas container is resized, but you can call this method manually if you change the size of the canvas nodes container element.

你可以调用不带参数的 .resize() 以使图表采用其容器元素的大小,或者你可以传递显式尺寸(例如,对于 printing)。

¥You can call .resize() with no parameters to have the chart take the size of its container element, or you can pass explicit dimensions (e.g., for printing).

// Resizes & redraws to fill its container element
myLineChart.resize();
// => returns 'this' for chainability
// With an explicit size:
myLineChart.resize(width, height);

# .clear()

将清除图表画布。在动画帧之间广泛使用,但你可能会发现它很有用。

¥Will clear the chart canvas. Used extensively internally between animation frames, but you might find it useful.

// Will clear the canvas that myLineChart is drawn on
myLineChart.clear();
// => returns 'this' for chainability

# .toBase64Image(type?, quality?)

这将返回处于当前状态的图表的 base 64 编码字符串。

¥This returns a base 64 encoded string of the chart in its current state.

myLineChart.toBase64Image();
// => returns png data url of the image on the canvas
myLineChart.toBase64Image('image/jpeg', 1)
// => returns a jpeg data url in the highest quality of the canvas

# .getElementsAtEventForMode(e, mode, options, useFinalPosition)

在传递事件和模式的 Chart 实例上调用 getElementsAtEventForMode(e, mode, options, useFinalPosition) 将返回找到的元素。optionsuseFinalPosition 参数传递给处理程序。

¥Calling getElementsAtEventForMode(e, mode, options, useFinalPosition) on your Chart instance passing an event and a mode will return the elements that are found. The options and useFinalPosition arguments are passed through to the handlers.

要获取被点击的项目,可以使用 getElementsAtEventForMode

¥To get an item that was clicked on, getElementsAtEventForMode can be used.

function clickHandler(evt) {
    const points = myChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);
    if (points.length) {
        const firstPoint = points[0];
        const label = myChart.data.labels[firstPoint.index];
        const value = myChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
    }
}

# .getSortedVisibleDatasetMetas()

按照在未隐藏的画布上绘制的顺序返回所有数据集元的数组。

¥Returns an array of all the dataset meta's in the order that they are drawn on the canvas that are not hidden.

const visibleMetas = chart.getSortedVisibleDatasetMetas();

# .getDatasetMeta(index)

查找与当前索引匹配的数据集并返回该元数据。此返回的数据包含用于构建图表的所有元数据。

¥Looks for the dataset that matches the current index and returns that metadata. This returned data has all of the metadata that is used to construct the chart.

元数据的 data 属性将包含有关每个点、柱等的信息,具体取决于图表类型。

¥The data property of the metadata will contain information about each point, bar, etc. depending on the chart type.

Chart.js 测试 (opens new window) 中提供了广泛的用法示例。

¥Extensive examples of usage are available in the Chart.js tests (opens new window).

const meta = myChart.getDatasetMeta(0);
const x = meta.data[0].x;

# getVisibleDatasetCount

返回当前未隐藏的数据集的数量。

¥Returns the number of datasets that are currently not hidden.

const numberOfVisibleDatasets = chart.getVisibleDatasetCount();

# setDatasetVisibility(datasetIndex, visibility)

设置给定数据集的可见性。这可用于在 HTML 中构建图表图例。在单击其中一个 HTML 项目期间,你可以调用 setDatasetVisibility 来更改相应的数据集。

¥Sets the visibility for a given dataset. This can be used to build a chart legend in HTML. During click on one of the HTML items, you can call setDatasetVisibility to change the appropriate dataset.

chart.setDatasetVisibility(1, false); // hides dataset at index 1
chart.update(); // chart now renders with dataset hidden

# toggleDataVisibility(index)

切换项目在所有数据集中的可见性。数据集需要明确支持此功能才能发挥作用。从内部图表类型、环形图/饼图、极地区域和柱状图中使用它。

¥Toggles the visibility of an item in all datasets. A dataset needs to explicitly support this feature for it to have an effect. From internal chart types, doughnut / pie, polar area, and bar use this.

chart.toggleDataVisibility(2); // toggles the item in all datasets, at index 2
chart.update(); // chart now renders with item hidden

# getDataVisibility(index)

返回所有数据集的数据索引的存储可见性状态。由 toggleDataVisibility 设置。数据集控制器应使用此方法来确定项目是否不可见。

¥Returns the stored visibility state of a data index for all datasets. Set by toggleDataVisibility. A dataset controller should use this method to determine if an item should not be visible.

const visible = chart.getDataVisibility(2);

# hide(datasetIndex, dataIndex?)

如果未指定 dataIndex,则将给定数据集的可见性设置为 false。更新图表并使用 'hide' 模式为数据集设置动画。这个动画可以在动画选项的 hide 键下配置。有关详细信息,请参阅 animations 文档。

¥If dataIndex is not specified, sets the visibility for the given dataset to false. Updates the chart and animates the dataset with 'hide' mode. This animation can be configured under the hide key in animation options. Please see animations docs for more details.

如果指定了 dataIndex,则将该元素的隐藏标志设置为 true 并更新图表。

¥If dataIndex is specified, sets the hidden flag of that element to true and updates the chart.

chart.hide(1); // hides dataset at index 1 and does 'hide' animation.
chart.hide(0, 2); // hides the data element at index 2 of the first dataset.

# show(datasetIndex, dataIndex?)

如果未指定 dataIndex,则将给定数据集的可见性设置为 true。更新图表并使用 'show' 模式为数据集设置动画。这个动画可以在动画选项的 show 键下配置。有关详细信息,请参阅 animations 文档。

¥If dataIndex is not specified, sets the visibility for the given dataset to true. Updates the chart and animates the dataset with 'show' mode. This animation can be configured under the show key in animation options. Please see animations docs for more details.

如果指定了 dataIndex,则将该元素的隐藏标志设置为 false 并更新图表。

¥If dataIndex is specified, sets the hidden flag of that element to false and updates the chart.

chart.show(1); // shows dataset at index 1 and does 'show' animation.
chart.show(0, 2); // shows the data element at index 2 of the first dataset.

# setActiveElements(activeElements)

设置图表的活动(悬停)元素。请参阅 "程序化事件" 示例文件以了解实际情况。

¥Sets the active (hovered) elements for the chart. See the "Programmatic Events" sample file to see this in action.

chart.setActiveElements([
    {datasetIndex: 0, index: 1},
]);

# isPluginEnabled(pluginId)

如果具有给定 ID 的插件已注册到图表实例,则返回一个布尔值。

¥Returns a boolean if a plugin with the given ID has been registered to the chart instance.

chart.isPluginEnabled('filler');

# 静态:getChart(key)

¥Static: getChart(key)

从给定键查找图表实例。如果键是 string,则它被解释为图表的 Canvas 节点的 ID。密钥也可以是 CanvasRenderingContext2DHTMLDOMElement。如果未找到图表,这将返回 undefined。要找到该图表,必须之前已创建该图表。

¥Finds the chart instance from the given key. If the key is a string, it is interpreted as the ID of the Canvas node for the Chart. The key can also be a CanvasRenderingContext2D or an HTMLDOMElement. This will return undefined if no Chart is found. To be found, the chart must have previously been created.

const chart = Chart.getChart("canvas-id");

# 静态:register(chartComponentLike)

¥Static: register(chartComponentLike)

用于将插件、轴类型或图表类型全局注册到所有图表。

¥Used to register plugins, axis types or chart types globally to all your charts.

import { Chart, Tooltip, LinearScale, PointElement, BubbleController } from 'chart.js';
Chart.register(Tooltip, LinearScale, PointElement, BubbleController);

# 静态:unregister(chartComponentLike)

¥Static: unregister(chartComponentLike)

用于从所有图表中全局注销插件、轴类型或图表类型。

¥Used to unregister plugins, axis types or chart types globally from all your charts.