new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Chart.js · all subjects

plugins

175 notes in this subject, read out of this brain and free to use. This is page 1 of 3.

Custom plugin for image canvas background

To draw an image as a canvas background, create a plugin with id 'customCanvasBackgroundImage' that uses the beforeDraw hook. Check if the image is complete; if so, get the chart context and chartArea (top, left, width, height), calculate centered position x = left + width / 2 - image.width / 2 and y = top + height / 2 - image.height / 2, then call ctx.drawImage(image, x, y). If the image is not loaded, set image.onload to redraw the chart.

Plugin beforeDraw hook receives chart, args, and options

The beforeDraw hook in a custom plugin receives three parameters: chart (the chart instance), args (hook arguments), and options (the plugin configuration options).

Plugin CSS alternative for canvas background

For normal chart display without export requirements, set the canvas background using CSS instead of a custom plugin. This is simpler and more performant than drawing to the canvas.

Canvas background no built-in support

Chart.js has no built-in support for canvas background images or colors. To add a background to a chart, you must write a custom plugin. This approach is necessary only if you want to export the chart with a specific background. For normal display, CSS background properties are easier to use.

Custom plugin for solid color canvas background

To draw a solid color background on a canvas, create a plugin with id 'customCanvasBackgroundColor' that uses the beforeDraw hook. In the hook, save the canvas context, set globalCompositeOperation to 'destination-over', set fillStyle to the desired color (default '#99ffff'), call fillRect(0, 0, chart.width, chart.height), and restore the context. The color can be configured via options.color in the plugin options.

LTTB decimation

LTTB (Largest Triangle Three Bucket) decimation reduces the number of data points significantly and is most useful for showing trends in data using only a few data points.

Decimation plugin configuration options table

The decimation plugin supports the following configuration options: | Name | Type | Default | Description | |------|------|---------|-------------| | `enabled` | boolean | `false` | Is decimation enabled? | | `algorithm` | string | `'min-max'` | Decimation algorithm to use. Options are `'lttb'` or `'min-max'`. | | `samples` | number | (none) | If the `'lttb'` algorithm is used, this is the number of samples in the output dataset. Defaults to the canvas width to pick 1 sample per pixel. | | `threshold` | number | (none) | If the number of samples in the current axis range is above this value, the decimation will be triggered. Defaults to 4 times the canvas width. The number of points after decimation can be higher than the threshold value. |

Decimation plugin requirements

To use the decimation plugin, all of the following requirements must be met: (1) The dataset must have an `indexAxis` of `'x'`. (2) The dataset must be a line chart. (3) The X axis for the dataset must be either a `'linear'` or `'time'` type axis. (4) Data must not need parsing, meaning `parsing` must be `false`. (5) The dataset object must be mutable; the plugin stores the original data as `dataset._data` and then defines a new `data` property on the dataset. (6) There must be more points on the chart than the threshold value.

Decimation algorithms available

The decimation plugin supports two algorithms: `'lttb'` (Largest Triangle Three Bucket) and `'min-max'`. The default algorithm is `'min-max'`.

Decimation plugin use case

The decimation plugin can be used with line charts to automatically decimate data at the start of the chart lifecycle.

Decimation plugin configuration namespace

The decimation plugin configuration options are located at `options.plugins.decimation`, and global defaults are defined in `Chart.defaults.plugins.decimation`.

Min-max decimation

Min-max decimation preserves peaks in data but could require up to 4 points for each pixel. This type of decimation works well for a very noisy signal where you need to see data peaks.

Inline plugins in chart configuration

Inline plugins can be included in the plugins array in the chart configuration. This is an alternative way of adding plugins for a single chart instance, as opposed to registering the plugin globally.

Limit plugin events with plugin options

Events for each plugin can be limited by defining an `events` array in the plugin options. For example, to have the tooltip only receive click events, set `options.plugins.tooltip.events` to `['click']` even if the chart listens to other events globally.

Capture events outside chartArea with plugin beforeEvent

Events that do not fire over chartArea, like `mouseout`, can be captured using a plugin with a `beforeEvent` hook. The hook receives the chart, event arguments, and plugin options.

Legend configuration namespace and overrides

Legend options are configured in the namespace `options.plugins.legend`. Global legend options are defined in `Chart.defaults.plugins.legend`. The doughnut, pie, and polar area charts override the legend defaults. To change the overrides for those chart types, options are defined in `Chart.overrides[type].plugins.legend`.

Legend label configuration table

Namespace: `options.plugins.legend.labels` | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `boxWidth` | `number` | `40` | Width of coloured box. | | `boxHeight` | `number` | `font.size` | Height of the coloured box. | | `color` | `Color` | `Chart.defaults.color` | Color of label and the strikethrough. | | `font` | `Font` | `Chart.defaults.font` | See Fonts. | | `padding` | `number` | `10` | Padding between rows of colored boxes. | | `generateLabels` | `function` | | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. | | `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data. | | `sort` | `function` | `null` | Sorts legend items. Type is `sort(a: LegendItem, b: LegendItem, data: ChartData): number;`. | | `pointStyle` | `pointStyle` | `'circle'` | If specified, this style of point is used for the legend. Only used if `usePointStyle` is true. | | `textAlign` | `string` | `'center'` | Horizontal alignment of the label text. Options are: `'left'`, `'right'` or `'center'`. | | `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on pointStyleWidth or the minimum value between boxWidth and font.size). | | `pointStyleWidth` | `number` | `null` | If `usePointStyle` is true, the width of the point style used for the legend. | | `useBorderRadius` | `boolean` | `false` | Label borderRadius will match corresponding borderRadius. | | `borderRadius` | `number` | `undefined` | Override the borderRadius to use. |

Legend configuration options table

| Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `display` | `boolean` | `true` | Is the legend shown? | | `position` | `string` | `'top'` | Position of the legend. | | `align` | `string` | `'center'` | Alignment of the legend. | | `maxHeight` | `number` | | Maximum height of the legend, in pixels | | `maxWidth` | `number` | | Maximum width of the legend, in pixels | | `fullSize` | `boolean` | `true` | Marks that this box should take the full width/height of the canvas (moving other boxes). | | `onClick` | `function` | | A callback that is called when a click event is registered on a label item. Arguments: `[event, legendItem, legend]`. | | `onHover` | `function` | | A callback that is called when a 'mousemove' event is registered on top of a label item. Arguments: `[event, legendItem, legend]`. | | `onLeave` | `function` | | A callback that is called when a 'mousemove' event is registered outside of a previously hovered label item. Arguments: `[event, legendItem, legend]`. | | `reverse` | `boolean` | `false` | Legend will show datasets in reverse order. | | `labels` | `object` | | See the Legend Label Configuration section. | | `rtl` | `boolean` | | `true` for rendering the legends from right to left. | | `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'` or `'ltr'` on the canvas for rendering the legend. | | `title` | `object` | | See the Legend Title Configuration section. |

Default legend click handler behavior

The default legend click handler toggles dataset visibility. When a legend item is clicked, if the dataset is visible it is hidden and `legendItem.hidden` is set to true. If the dataset is hidden it is shown and `legendItem.hidden` is set to false. The handler signature is `function(e, legendItem, legend)`.

Legend align options

The legend alignment options are `'start'`, `'center'`, and `'end'`. The default is `'center'` for unrecognized values.

Legend Item interface

Items passed to the legend `onClick` function are returned from `labels.generateLabels`. Legend items must implement the following interface: ```javascript { text: string, borderRadius?: number | BorderRadius, datasetIndex: number, fillStyle: Color, fontColor: Color, hidden: boolean, lineCap: string, lineDash: number[], lineDashOffset: number, lineJoin: string, lineWidth: number, strokeStyle: Color, pointStyle: string | Image | HTMLCanvasElement, rotation: number } ```

Legend title configuration table

Namespace: `options.plugins.legend.title` | Name | Type | Default | Description | | ---- | ---- | ------- | ----------- | | `color` | `Color` | `Chart.defaults.color` | Color of text. | | `display` | `boolean` | `false` | Is the legend title displayed. | | `font` | `Font` | `Chart.defaults.font` | See Fonts. | | `padding` | `Padding` | `0` | Padding around the title. | | `text` | `string` | | The string title. |

Legend configuration with red text example

This example creates a bar chart with the legend enabled and sets all legend text to red: ```javascript const chart = new Chart(ctx, { type: 'bar', data: data, options: { plugins: { legend: { display: true, labels: { color: 'rgb(255, 99, 132)' } } } } }); ```

Custom legend click handler to link dataset visibility

This example creates a custom legend click handler that links the visibility of the first two datasets together: ```javascript const defaultLegendClickHandler = Chart.defaults.plugins.legend.onClick; const pieDoughnutLegendClickHandler = Chart.controllers.doughnut.overrides.plugins.legend.onClick; const newLegendClickHandler = function (e, legendItem, legend) { const index = legendItem.datasetIndex; const type = legend.chart.config.type; if (index > 1) { // Do the original logic if (type === 'pie' || type === 'doughnut') { pieDoughnutLegendClickHandler(e, legendItem, legend) } else { defaultLegendClickHandler(e, legendItem, legend); } } else { let ci = legend.chart; [ ci.getDatasetMeta(0), ci.getDatasetMeta(1) ].forEach(function(meta) { meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null; }); ci.update(); } }; const chart = new Chart(ctx, { type: 'line', data: data, options: { plugins: { legend: { onClick: newLegendClickHandler } } } }); ```

Legend position options

The legend position can be set to `'top'`, `'left'`, `'bottom'`, `'right'`, or `'chartArea'`. When using `'chartArea'`, the legend position is not configurable and will always appear on the left side of the chart in the middle.

Subtitle example with display and text

This example shows how to enable a subtitle with the text 'Custom Chart Subtitle' on a line chart: ```javascript const chart = new Chart(ctx, { type: 'line', data: data, options: { plugins: { subtitle: { display: true, text: 'Custom Chart Subtitle' } } } }); ```

Subtitle has same options as title

The subtitle has exactly the same configuration options as the main title. The only difference is the namespace where they are configured.

Subtitle configuration namespace

The subtitle configuration is located at options.plugins.subtitle. Global defaults for subtitle are configured in Chart.defaults.plugins.subtitle.

Subtitle positioning

By default, the subtitle is placed under the main title on the chart.

Title plugin namespace and defaults

The title plugin configuration is located at `options.plugins.title`. Global defaults for the title plugin are defined in `Chart.defaults.plugins.title`.

Title configuration options

The title plugin supports the following options: | Name | Type | Default | Scriptable | Description | | ---- | ---- | ------- | :----: | ----------- | | `align` | `string` | `'center'` | Yes | Alignment of the title. Options are 'start', 'center', 'end'. | | `color` | `Color` | `Chart.defaults.color` | Yes | Color of text. | | `display` | `boolean` | `false` | Yes | Is the title shown? | | `fullSize` | `boolean` | `true` | Yes | Marks that this box should take the full width/height of the canvas. If `false`, the box is sized and placed above/beside the chart area. | | `position` | `string` | `'top'` | Yes | Position of title. Options are 'top', 'left', 'bottom', 'right'. | | `font` | `Font` | `{weight: 'bold'}` | Yes | Font configuration. See Fonts documentation. | | `padding` | `Padding` | `10` | Yes | Padding to apply around the title. Only `top` and `bottom` are implemented. | | `text` | `string`\|`string[]` | `''` | Yes | Title text to display. If specified as an array, text is rendered on multiple lines. |

Title position values

The title position option accepts the following values: 'top', 'left', 'bottom', 'right'.

Title visual customization with HTML and CSS

If you need more visual customizations for titles than the built-in options provide, you can implement the title with HTML and CSS instead.

Basic title example

This example shows how to enable a title on a chart: ```javascript const chart = new Chart(ctx, { type: 'line', data: data, options: { plugins: { title: { display: true, text: 'Custom Chart Title' } } } }); ```

Title alignment values

The title align option accepts the following values: 'start', 'center', 'end'.

Title with custom padding example

This example shows how to specify separate top and bottom title text padding: ```javascript const chart = new Chart(ctx, { type: 'line', data: data, options: { plugins: { title: { display: true, text: 'Custom Chart Title', padding: { top: 10, bottom: 30 } } } } }); ```

Chart.unregister(chartComponentLike) static method

Chart.unregister(chartComponentLike) is used to unregister plugins, axis types or chart types globally from all your charts.

.isPluginEnabled(pluginId) method

isPluginEnabled(pluginId) returns a boolean indicating if a plugin with the given ID has been registered to the chart instance.

Chart.register(chartComponentLike) static method

Chart.register(chartComponentLike) is used to register plugins, axis types or chart types globally to all your charts.

Tooltip caret alignment with xAlign and yAlign

The `xAlign` and `yAlign` options define the position of the tooltip caret. If these parameters are unset, the optimal caret position is determined automatically. Supported `xAlign` values are: `'left'`, `'center'`, `'right'`. Supported `yAlign` values are: `'top'`, `'center'`, `'bottom'`.

Tooltip text alignment options

The `titleAlign`, `bodyAlign` and `footerAlign` options define the horizontal position of the text lines with respect to the tooltip box. Supported values are: `'left'` (default), `'right'`, `'center'`. These options are only applied to text lines; color boxes are always aligned to the left edge.

Tooltip model properties

The tooltip model contains the following properties that can be used to render the tooltip: ```javascript { chart: Chart, // The items that we are rendering in the tooltip 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 } ```

Tooltip configuration namespace

Tooltip configuration is defined in the namespace `options.plugins.tooltip`. Global options for chart tooltips are defined in `Chart.defaults.plugins.tooltip`.

Tooltip position modes

Tooltip position modes determine where the tooltip is placed relative to the element or event position. Possible modes are: `'average'` and `'nearest'`. The `'average'` mode places the tooltip at the average position of the items displayed in the tooltip. The `'nearest'` mode places the tooltip at the position of the element closest to the event position. Custom position modes can also be defined.

Tooltip configuration options table

Tooltip configuration options: | Name | Type | Default | Description | | ---- | ---- | ------- | -----------| | `enabled` | `boolean` | `true` | Are on-canvas tooltips enabled? | | `external` | `function` | `null` | See external tooltip section. | | `mode` | `string` | `interaction.mode` | Sets which elements appear in the tooltip. | | `intersect` | `boolean` | `interaction.intersect` | If true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times. | | `position` | `string` | `'average'` | The mode for positioning the tooltip. | | `callbacks` | `object` | | See the callbacks section. | | `itemSort` | `function` | | Sort tooltip items. | | `filter` | `function` | | Filter tooltip items. | | `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.8)'` | Background color of the tooltip. | | `titleColor` | `Color` | `'#fff'` | Color of title text. | | `titleFont` | `Font` | `{weight: 'bold'}` | See Fonts. | | `titleAlign` | `string` | `'left'` | Horizontal alignment of the title text lines. | | `titleSpacing` | `number` | `2` | Spacing to add to top and bottom of each title line. | | `titleMarginBottom` | `number` | `6` | Margin to add on bottom of title section. | | `bodyColor` | `Color` | `'#fff'` | Color of body text. | | `bodyFont` | `Font` | `{}` | See Fonts. | | `bodyAlign` | `string` | `'left'` | Horizontal alignment of the body text lines. | | `bodySpacing` | `number` | `2` | Spacing to add to top and bottom of each tooltip item. | | `footerColor` | `Color` | `'#fff'` | Color of footer text. | | `footerFont` | `Font` | `{weight: 'bold'}` | See Fonts. | | `footerAlign` | `string` | `'left'` | Horizontal alignment of the footer text lines. | | `footerSpacing` | `number` | `2` | Spacing to add to top and bottom of each footer line. | | `footerMarginTop` | `number` | `6` | Margin to add before drawing the footer. | | `padding` | `Padding` | `6` | Padding inside the tooltip. | | `caretPadding` | `number` | `2` | Extra distance to move the end of the tooltip arrow away from the tooltip point. | | `caretSize` | `number` | `5` | Size, in px, of the tooltip arrow. | | `cornerRadius` | `number` or `object` | `6` | Radius of tooltip corner curves. | | `multiKeyBackground` | `Color` | `'#fff'` | Color to draw behind the colored boxes when multiple items are in the tooltip. | | `displayColors` | `boolean` | `true` | If true, color boxes are shown in the tooltip. | | `boxWidth` | `number` | `bodyFont.size` | Width of the color box if displayColors is true. | | `boxHeight` | `number` | `bodyFont.size` | Height of the color box if displayColors is true. | | `boxPadding` | `number` | `1` | Padding between the color box and the text. | | `usePointStyle` | `boolean` | `false` | Use the corresponding point style (from dataset options) instead of color boxes, ex: star, triangle etc. (size is based on the minimum value between boxWidth and boxHeight). | | `borderColor` | `Color` | `'rgba(0, 0, 0, 0)'` | Color of the border. | | `borderWidth` | `number` | `0` | Size of the border. | | `rtl` | `boolean` | | `true` for rendering the tooltip from right to left. | | `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'` or `'ltr'` on the canvas for rendering the tooltips, regardless of the css specified on the canvas. | | `xAlign` | `string` | `undefined` | Position of the tooltip caret in the X direction. | | `yAlign` | `string` | `undefined` | Position of the tooltip caret in the Y direction. |

Sort callback for tooltip items

The `itemSort` callback allows sorting of tooltip items. It 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.

External tooltip configuration

External tooltips allow you to hook into the tooltip rendering process so that you can render the tooltip in your own custom way. This is generally 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` properties. External tooltips can be enabled in the global or chart configuration.

Custom position mode example

Example of defining a custom tooltip position mode: ```javascript 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(ctx, { data, options: { plugins: { tooltip: { position: 'myCustomPositioner' } } } }) ```

Filter callback for tooltip items

The `filter` callback allows filtering of tooltip items. It 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 namespace and override

Tooltip callbacks are defined in the namespace `options.plugins.tooltip.callbacks`. Items can also be overridden per dataset in the namespace `data.datasets[].tooltip.callbacks`. For all callback functions, `this` will be the tooltip object created from the `Tooltip` constructor. If a callback returns `undefined`, the default callback will be used. To remove things from the tooltip, a callback should return an empty string.

Tooltip item context interface

A tooltip item context object passed to tooltip callbacks contains the following properties: ```javascript { // 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, } ```

Tooltip callback functions table

Tooltip callback functions and their parameters: | Name | Arguments | Return Type | Dataset override | Description | | ---- | --------- | ----------- | ---------------- | -----------| | `beforeTitle` | `TooltipItem[]` | `string \| string[] \| undefined` | | Returns the text to render before the title. | | `title` | `TooltipItem[]` | `string \| string[] \| undefined` | | Returns text to render as the title of the tooltip. | | `afterTitle` | `TooltipItem[]` | `string \| string[] \| undefined` | | Returns text to render after the title. | | `beforeBody` | `TooltipItem[]` | `string \| string[] \| undefined` | | Returns text to render before the body section. | | `beforeLabel` | `TooltipItem` | `string \| string[] \| undefined` | Yes | Returns text to render before an individual label. This will be called for each item in the tooltip. | | `label` | `TooltipItem` | `string \| string[] \| undefined` | Yes | Returns text to render for an individual item in the tooltip. | | `labelColor` | `TooltipItem` | `object \| undefined` | Yes | Returns the colors to render for the tooltip item. | | `labelTextColor` | `TooltipItem` | `Color \| undefined` | Yes | Returns the colors for the text of the label for the tooltip item. | | `labelPointStyle` | `TooltipItem` | `object \| undefined` | Yes | Returns the point style to use instead of color boxes if usePointStyle is true (object with values `pointStyle` and `rotation`). | | `afterLabel` | `TooltipItem` | `string \| string[] \| undefined` | Yes | Returns text to render after an individual label. | | `afterBody` | `TooltipItem[]` | `string \| string[] \| undefined` | | Returns text to render after the body section. | | `beforeFooter` | `TooltipItem[]` | `string \| string[] \| undefined` | | Returns text to render before the footer section. | | `footer` | `TooltipItem[]` | `string \| string[] \| undefined` | | Returns text to render as the footer of the tooltip. | | `afterFooter` | `TooltipItem[]` | `string \| string[] \| undefined` | | Text to render after the footer section. |

Label callback example - currency formatting

Example of using the label callback to format tooltip values with currency: ```javascript 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; } } } } } }); ```

External tooltip example - HTML table

Example of creating a custom HTML tooltip that renders as a table: ```javascript 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'; } } } } }); ```

TypeScript custom position mode registration

When using TypeScript with custom tooltip position modes, you need to register the new mode in the `TooltipPositionerMap` interface: ```typescript declare module 'chart.js' { interface TooltipPositionerMap { myCustomPositioner: TooltipPositionerFunction<ChartType>; } } ```

Label color callback example

Example of using the labelColor callback to customize the color box appearance and labelTextColor callback to customize label text color: ```javascript 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 example

Example of using the labelPointStyle callback to draw custom point styles instead of color boxes in the tooltip: ```javascript const chart = new Chart(ctx, { type: 'line', data: data, options: { plugins: { tooltip: { usePointStyle: true, callbacks: { labelPointStyle: function(context) { return { pointStyle: 'triangle', rotation: 0 }; } } } } } }); ```

Custom tooltip position modes

New tooltip position modes can be defined by adding functions to the `Chart.Tooltip.positioners` map. A custom positioner function receives `elements` (the tooltip elements) and `eventPosition` (the position of the event in canvas coordinates) as parameters, and must return a position object with `x` and `y` properties. Optionally, `xAlign` and `yAlign` can be included in the return object to override those tooltip options.

Default font overrides for tooltip

By default, the `titleFont`, `bodyFont` and `footerFont` options listen to the `Chart.defaults.font` options for setting their values. Overriding these normally by accessing the object won't work because they are backed by a get function that looks to the default `font` namespace. To override these, you need to replace the get function with your own function that returns the desired config. Example: `Chart.defaults.plugins.tooltip.titleFont = () => ({ size: 20, lineHeight: 1.2, weight: 800 });`

Tooltip font property warning

The `titleFont`, `bodyFont` and `footerFont` options default to the `Chart.defaults.font` options. To change the overrides for those options, you will need to pass a function that returns a font object, rather than setting the font object directly.

Give your agent this brain