devicePixelRatio for bitmap and print rendering
For applications where a chart will be converted to a bitmap or printed to a higher DPI medium, setting devicePixelRatio to a value other than 1 will force the canvas size to be scaled by that amount relative to the container size. There will be no visible difference on screen; the difference will only be visible when the image is zoomed or printed.
devicePixelRatio option configuration
The devicePixelRatio option is located in the options namespace. It accepts a number type with a default value of window.devicePixelRatio. This option overrides the window's default devicePixelRatio.
devicePixelRatio default behavior
By default, the chart's canvas uses a 1:1 pixel ratio unless the physical display has a higher pixel ratio, such as Retina displays.
Global configuration example: interaction mode
Setting Chart.defaults.interaction.mode = 'nearest' applies the 'nearest' interaction mode to all charts where this is not overridden by chart type defaults or options passed to the constructor. Individual chart options override this global setting.
Chart.js configuration object structure
The top level structure of Chart.js configuration contains four properties: type (string, determines the main type of the chart), data (object containing chart data), options (object containing configuration options), and plugins (array of inline plugins).
Dataset-level configuration options
Options can be configured directly on individual datasets. Dataset options are resolved at multiple levels, allowing defaults to be set at the dataset type level and then overridden on specific dataset instances.
Dataset default configuration example
Setting Chart.defaults.datasets.line.showLine = false disables line display for all line datasets by default. Individual datasets can override this by setting showLine: true on that specific dataset. Datasets with a different type (e.g., 'scatter') are not affected by the 'line' dataset defaults.
Global configuration with Chart.defaults
Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. The global general options are defined in Chart.defaults. This allows setting default behavior across all chart instances while still allowing individual charts to override these settings.
layout configuration options
The layout configuration is defined in the namespace options.layout. The global options for chart layout are defined in Chart.defaults.layout. Layout accepts two options: autoPadding (boolean, default true, not scriptable) which applies automatic padding so visible elements are completely drawn, and padding (Padding type, default 0, scriptable) which specifies the padding to add inside the chart.
autoPadding option
The autoPadding option is a boolean that defaults to true. When enabled, it automatically applies padding so that visible elements are completely drawn within the chart area. This option is not scriptable.
padding option
The padding option accepts a Padding value and defaults to 0. It specifies the padding to add inside the chart. This option is scriptable, allowing padding to be set based on context.
Hover and tooltip options extend from interaction options
`options.hover` and `options.plugins.tooltip` extend from `options.interaction`. If `mode`, `intersect`, or other common settings are configured only in `options.interaction`, both hover and tooltip interactions will obey those settings.
Interaction intersect parameter
The `intersect` option is a boolean with default value `true`. When true, the interaction mode only applies when the mouse position intersects an item on the chart.
Interaction mode parameter
The `mode` option in the interaction configuration sets which elements appear in the interaction. It is a string with default value `'nearest'`. See Interaction Modes documentation for available modes.
onClick callback function
The `onClick` option is a function with default value `null`. It is called if the event is of type `'mouseup'`, `'click'` or `'contextmenu'` over chartArea. It is passed the event, an array of active elements, and the chart.
Events option configuration
The `events` option is a string array that defines the browser events the chart should listen to. Default value is `['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']`. Each of these events triggers hover and is passed to plugins.
Configure chart to respond only to click events
To restrict a chart to only respond to click events, set `options.events` to `['click']` in the chart configuration.
Interaction options namespace and configuration location
Interaction options are configured in the `options.interaction` namespace. The global interaction configuration is available at `Chart.defaults.interaction`.
Interaction axis parameter
The `axis` option is a string that can be set to `'x'`, `'y'`, `'xy'` or `'r'` to define which directions are used in calculating distances. It defaults to `'x'` for `'index'` mode and `'xy'` in `'dataset'` and `'nearest'` modes.
Interaction includeInvisible parameter
The `includeInvisible` option is a boolean with default value `false`. When true, invisible points that are outside of the chart area will also be included when evaluating interactions.
Interaction mode index
The `'index'` interaction mode finds items at the same index. If `intersect` is true, the first intersecting item is used to determine the index in the data. If `intersect` is false, the nearest item in the x direction is used to determine the index. For horizontal bar charts, set `axis` to `'y'` to search along the y direction instead.
Convert event coordinates to data values
To convert mouse event coordinates to data values on a chart, use `Chart.helpers.getRelativePosition(e, chart)` to get canvas position, then call `chart.scales.x.getValueForPixel()` and `chart.scales.y.getValueForPixel()` with the canvas position coordinates to get data values.
Interaction mode x
The `'x'` interaction mode returns all items that would intersect based on the X coordinate of the mouse position only. This is useful for a vertical cursor implementation. This mode only applies to cartesian charts.
Interaction mode nearest
The `'nearest'` interaction mode gets the items at the nearest distance to the mouse position. The nearest item is determined based on distance to the center of the chart item (point, bar). The `axis` setting can define which coordinates are considered in distance calculation. If `intersect` is true, this is only triggered when the mouse position intersects an item on the graph.
Interaction options apply to hover and tooltip by default
Options configured in `options.interaction` apply to both the hover and tooltip interactions by default. The same options can be set in `options.hover` to affect only hover interaction, or in `options.plugins.tooltip` to configure only tooltip interactions.
onHover callback function
The `onHover` option is a function with default value `null`. It is called when any chart events fire over the chartArea. It is passed the event, an array of active elements (bars, points, etc), and the chart.
Create custom interaction modes
New interaction modes can be defined by adding functions to the `Chart.Interaction.modes` map. Custom modes receive the chart, the event, options, and a useFinalPosition flag. They should return an array of InteractionItem objects. The `Chart.Interaction.evaluateInteractionItems` function can be used to help implement custom modes.
Interaction mode y
The `'y'` interaction mode returns all items that would intersect based on the Y coordinate of the mouse position. This is useful for a horizontal cursor implementation. This mode only applies to cartesian charts.
Register custom interaction mode in TypeScript
In TypeScript, custom interaction modes must also be registered by declaring a module augmentation for the `InteractionModeMap` interface: `declare module 'chart.js' { interface InteractionModeMap { myCustomMode: InteractionModeFunction; } }`
Custom interaction mode example
import { Interaction } from 'chart.js';
import { getRelativePosition } from 'chart.js/helpers';
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;
};
new Chart(ctx, {
type: 'line',
data: data,
options: {
interaction: {
mode: 'myCustomMode'
}
}
});
Interaction mode dataset
The `'dataset'` interaction mode finds items in the same dataset. If `intersect` is true, the first intersecting item is used to determine the index in the data. If `intersect` is false, the nearest item is used to determine the index.
Interaction mode point
The `'point'` interaction mode finds all items that intersect the mouse position.
Canvas render size vs display size distinction
The canvas render size (canvas.width and canvas.height) cannot be expressed with relative values, but the display size (canvas.style.width and canvas.style.height) can. These sizes are independent of each other, and the canvas render size does not adjust automatically based on display size, which makes rendering inaccurate if they are not synchronized.
Responsive configuration options
Configuration options for responsive charts under the `options` namespace: `responsive` (boolean, default true) resizes the chart canvas when its container does; `maintainAspectRatio` (boolean, default true) maintains the original canvas aspect ratio when resizing; `aspectRatio` (number, default 1 or 2) sets canvas aspect ratio (width / height), where 1 is square, with radial charts defaulting to 1 and others defaulting to 2, and this option is ignored if height is explicitly defined; `onResize` (function, default null) is called when a resize occurs with the chart instance and new size as arguments; `resizeDelay` (number, default 0) delays the resize update by milliseconds to ease the process.
Proper container setup for responsive charts
Chart.js detects canvas size changes using the parent container, not the canvas element directly. The container must be relatively positioned and dedicated to the chart canvas only. Responsiveness is achieved by setting relative values for the container size. The HTML structure should be: a div with class and style 'position: relative' plus relative height and width values (e.g., 'height:40vh; width:80vw'), containing a canvas element.
Programmatic chart resizing
Charts can be programmatically resized by modifying the container size using: chart.canvas.parentNode.style.height = '128px'; chart.canvas.parentNode.style.width = '128px';. For this code to correctly resize the chart height, the maintainAspectRatio option must also be set to false.
Flexbox and Grid layout with charts
To prevent overflow issues when using flexbox or grid layout, set the flex or grid child element to have a min-width of 0. This prevents the chart container from expanding beyond its intended size.
Resizing charts for printing
CSS media queries may cause charts to need resizing when printing, but the resize won't happen automatically. To support resizing when printing, hook the onbeforeprint event and manually trigger Chart.instances[id].resize() for each chart. Alternatively, use beforeprint to call resize(600, 600) with explicit dimensions and afterprint to call resize() without arguments to restore automatic sizing.
Example: grid layout with chart
<div class="grid-container" style="display: grid">
<div class="chart-container" style="min-width: 0">
<canvas id="chart"></canvas>
</div>
</div>
Example: responsive chart container HTML
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
<canvas id="chart"></canvas>
</div>
Example: print resize handler
function beforePrintHandler () {
for (let id in Chart.instances) {
Chart.instances[id].resize();
}
}
Example: explicit size for print layout
window.addEventListener('beforeprint', () => {
myChart.resize(600, 600);
});
window.addEventListener('afterprint', () => {
myChart.resize();
});
Invalid responsive canvas approaches
Three common invalid approaches to making responsive canvases are: using height and width attributes with viewport units like '<canvas height="40vh" width="80vw">' (invalid values, canvas doesn't resize); using only inline style with viewport units like '<canvas style="height:40vh; width:80vw">' (invalid behavior, canvas becomes blurry); and applying margin styles directly to canvas like '<canvas style="margin: 0 auto;">' (invalid behavior, canvas continually shrinks).
.reset() method
reset() resets the chart to its state before the initial animation. A new animation can then be triggered using update().
.render() method
render() triggers a redraw of all chart elements. This does not update elements for new data; use .update() for that purpose.
.show(datasetIndex, dataIndex?) method
show(datasetIndex, dataIndex?) has two behaviors: 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. If dataIndex is specified, sets the hidden flag of that element to false and updates the chart.
.destroy() method
Use destroy() 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.
.resize(width?, height?) method
resize(width?, height?) manually resizes the canvas element. This is run each time the canvas container is resized, but can be called manually if the size of the canvas node's container element changes. Call .resize() with no parameters to have the chart take the size of its container element, or pass explicit dimensions. Returns 'this' for chainability.
.clear() method
clear() clears the chart canvas. It is used extensively internally between animation frames. Returns 'this' for chainability.
.getVisibleDatasetCount() method
getVisibleDatasetCount() returns the number of datasets that are currently not hidden.
.setActiveElements(activeElements) method
setActiveElements(activeElements) sets the active (hovered) elements for the chart. The activeElements parameter is an array of objects with { datasetIndex: number, index: number } properties.
.toBase64Image(type?, quality?) method
toBase64Image(type?, quality?) returns a base 64 encoded string of the chart in its current state. The type parameter specifies image format (e.g., 'image/jpeg'). The quality parameter ranges from 0 to 1 for image quality. Defaults to PNG format.
.getElementsAtEventForMode(e, mode, options, useFinalPosition) method
getElementsAtEventForMode(e, mode, options, useFinalPosition) returns the elements found at a given event and mode. The e parameter is an event, mode is the interaction mode (e.g., 'nearest'), options is an object (e.g., { intersect: true }), and useFinalPosition is a boolean indicating whether to use final element positions. Useful for getting items that were clicked on.
.toggleDataVisibility(index) method
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 feature.
.getDatasetMeta(index) method
getDatasetMeta(index) looks for the dataset that matches the given index and returns that metadata. This returned data has all of the metadata that is used to construct the chart. The data property of the metadata contains information about each point, bar, etc. depending on the chart type.
.update() method
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. The mode parameter can be a string value ('active', 'hide', 'reset', 'resize', 'show', 'none', or undefined) or a function that receives a context object { datasetIndex: number } and returns a mode string, allowing different modes per dataset.
.getSortedVisibleDatasetMetas() method
getSortedVisibleDatasetMetas() returns an array of all the dataset meta's in the order that they are drawn on the canvas that are not hidden.
.setDatasetVisibility(datasetIndex, visibility) method
setDatasetVisibility(datasetIndex, visibility) sets the visibility for a given dataset. This can be used to build a chart legend in HTML. During click on HTML items, call setDatasetVisibility to change the appropriate dataset visibility.
.getDataVisibility(index) method
getDataVisibility(index) returns the stored visibility state of a data index for all datasets. It is set by toggleDataVisibility(). A dataset controller should use this method to determine if an item should not be visible.
Chart.getChart(key) static method
Chart.getChart(key) 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 returns undefined if no Chart is found. To be found, the chart must have previously been created.