This commit is contained in:
Xes
2025-08-14 22:44:47 +02:00
parent 8ce45119b6
commit 791cb748ab
39112 changed files with 975901 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
# General Configuration
These sections describe general configuration options that can apply elsewhere in the documentation.
* [Responsive](./responsive.md) defines responsive chart options that apply to all charts.
* [Device Pixel Ratio](./device-pixel-ratio.md) defines the ratio between display pixels and rendered pixels.
* [Interactions](./interactions/README.md) defines options that reflect how hovering chart elements works.
* [Options](./options.md) scriptable and indexable options syntax.
* [Colors](./colors.md) defines acceptable color values.
* [Font](./fonts.md) defines various font options.
* [Performance](./performance.md) gives tips for performance-sensitive applications.

View File

@@ -0,0 +1,39 @@
# Accessible Charts
Chart.js charts are rendered on user provided `canvas` elements. Thus, it is up to the user to create the `canvas` element in a way that is accessible. The `canvas` element has support in all browsers and will render on screen but the `canvas` content will not be accessible to screen readers.
With `canvas`, the accessibility has to be added with ARIA attributes on the `canvas` element or added using internal fallback content placed within the opening and closing canvas tags.
This [website](http://pauljadam.com/demos/canvas.html) has a more detailed explanation of `canvas` accessibility as well as in depth examples.
## Examples
These are some examples of **accessible** `canvas` elements.
By setting the `role` and `aria-label`, this `canvas` now has an accessible name.
```html
<canvas id="goodCanvas1" width="400" height="100" aria-label="Hello ARIA World" role="img"></canvas>
```
This `canvas` element has a text alternative via fallback content.
```html
<canvas id="okCanvas2" width="400" height="100">
<p>Hello Fallback World</p>
</canvas>
```
These are some bad examples of **inaccessible** `canvas` elements.
This `canvas` element does not have an accessible name or role.
```html
<canvas id="badCanvas1" width="400" height="100"></canvas>
```
This `canvas` element has inaccessible fallback content.
```html
<canvas id="badCanvas2" width="400" height="100">Your browser does not support the canvas element.</canvas>
```

View File

@@ -0,0 +1,49 @@
# Colors
When supplying colors to Chart options, you can use a number of formats. You can specify the color as a string in hexadecimal, RGB, or HSL notations. If a color is needed, but not specified, Chart.js will use the global default color. This color is stored at `Chart.defaults.global.defaultColor`. It is initially set to `'rgba(0, 0, 0, 0.1)'`.
You can also pass a [CanvasGradient](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient) object. You will need to create this before passing to the chart, but using it you can achieve some interesting effects.
## Patterns and Gradients
An alternative option is to pass a [CanvasPattern](https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern) or [CanvasGradient](https://developer.mozilla.org/en/docs/Web/API/CanvasGradient) object instead of a string colour.
For example, if you wanted to fill a dataset with a pattern from an image you could do the following.
```javascript
var img = new Image();
img.src = 'https://example.com/my_image.png';
img.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
var fillPattern = ctx.createPattern(img, 'repeat');
var chart = new Chart(ctx, {
data: {
labels: ['Item 1', 'Item 2', 'Item 3'],
datasets: [{
data: [10, 20, 30],
backgroundColor: fillPattern
}]
}
});
};
```
Using pattern fills for data graphics can help viewers with vision deficiencies (e.g. color-blindness or partial sight) to [more easily understand your data](http://betweentwobrackets.com/data-graphics-and-colour-vision/).
Using the [Patternomaly](https://github.com/ashiguruma/patternomaly) library you can generate patterns to fill datasets.
```javascript
var chartData = {
datasets: [{
data: [45, 25, 20, 10],
backgroundColor: [
pattern.draw('square', '#ff6384'),
pattern.draw('circle', '#36a2eb'),
pattern.draw('diamond', '#cc65fe'),
pattern.draw('triangle', '#ffce56')
]
}],
labels: ['Red', 'Blue', 'Purple', 'Yellow']
};
```

View File

@@ -0,0 +1,13 @@
# Device Pixel Ratio
By default the chart's canvas will use a 1:1 pixel ratio, unless the physical display has a higher pixel ratio (e.g. Retina displays).
For applications where a chart will be converted to a bitmap, or printed to a higher DPI medium it can be desirable to render the chart at a higher resolution than the default.
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 should be no visible difference on screen; the difference will only be visible when the image is zoomed or printed.
## Configuration Options
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `devicePixelRatio` | `number` | `window.devicePixelRatio` | Override the window's default devicePixelRatio.

View File

@@ -0,0 +1,32 @@
# Fonts
There are 4 special global settings that can change all of the fonts on the chart. These options are in `Chart.defaults.global`. The global font settings only apply when more specific options are not included in the config.
For example, in this chart the text will all be red except for the labels in the legend.
```javascript
Chart.defaults.global.defaultFontColor = 'red';
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
labels: {
// This more specific font property overrides the global property
fontColor: 'black'
}
}
}
});
```
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `defaultFontColor` | `Color` | `'#666'` | Default font color for all text.
| `defaultFontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Default font family for all text.
| `defaultFontSize` | `number` | `12` | Default font size (in px) for text. Does not apply to radialLinear scale point labels.
| `defaultFontStyle` | `string` | `'normal'` | Default font style. Does not apply to tooltip title or footer. Does not apply to chart title.
## Missing Fonts
If a font is specified for a chart that does exist on the system, the browser will not apply the font when it is set. If you notice odd fonts appearing in your charts, check that the font you are applying exists on your system. See [issue 3318](https://github.com/chartjs/Chart.js/issues/3318) for more details.

View File

@@ -0,0 +1,10 @@
# Interactions
The hover configuration is passed into the `options.hover` namespace. The global hover configuration is at `Chart.defaults.global.hover`. To configure which events trigger chart interactions, see [events](./events.md#events).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `mode` | `string` | `'nearest'` | Sets which elements appear in the tooltip. See [Interaction Modes](./modes.md#interaction-modes) for details.
| `intersect` | `boolean` | `true` | if true, the hover mode only applies when the mouse position intersects an item on the chart.
| `axis` | `string` | `'x'` | Can be set to `'x'`, `'y'`, or `'xy'` to define which directions are used in calculating distances. Defaults to `'x'` for `'index'` mode and `'xy'` in `dataset` and `'nearest'` modes.
| `animationDuration` | `number` | `400` | Duration in milliseconds it takes to animate hover style changes.

View File

@@ -0,0 +1,21 @@
# Events
The following properties define how the chart interacts with events.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `events` | `string[]` | `['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']` | The `events` option defines the browser events that the chart should listen to for tooltips and hovering. [more...](#event-option)
| `onHover` | `function` | `null` | Called when any of the events fire. Called in the context of the chart and passed the event and an array of active elements (bars, points, etc).
| `onClick` | `function` | `null` | Called if the event is of type `'mouseup'` or `'click'`. Called in the context of the chart and passed the event and an array of active elements.
## Event Option
For example, to have the chart only respond to click events, you could do:
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
// This chart will not respond to mousemove, etc
events: ['click']
}
});
```

View File

@@ -0,0 +1,119 @@
# Interaction Modes
When configuring interaction with the graph via hover or tooltips, a number of different modes are available.
The modes are detailed below and how they behave in conjunction with the `intersect` setting.
## point
Finds all of the items that intersect the point.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'point'
}
}
});
```
## nearest
Gets the items that are at the nearest distance to the point. The nearest item is determined based on the distance to the center of the chart item (point, bar). You can use the `axis` setting to define which directions are used in distance calculation. If `intersect` is true, this is only triggered when the mouse position intersects an item in the graph. This is very useful for combo charts where points are hidden behind bars.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'nearest'
}
}
});
```
## single (deprecated)
Finds the first item that intersects the point and returns it. Behaves like `'nearest'` mode with `intersect = true`.
## label (deprecated)
See `'index'` mode.
## index
Finds item at the same index. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item, in the x direction, is used to determine the index.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'index'
}
}
});
```
To use index mode in a chart like the horizontal bar chart, where we search along the y direction, you can use the `axis` setting introduced in v2.7.0. By setting this value to `'y'` on the y direction is used.
```javascript
var chart = new Chart(ctx, {
type: 'horizontalBar',
data: data,
options: {
tooltips: {
mode: 'index',
axis: 'y'
}
}
});
```
## x-axis (deprecated)
Behaves like `'index'` mode with `intersect = false`.
## dataset
Finds items in the same dataset. If the `intersect` setting is true, the first intersecting item is used to determine the index in the data. If `intersect` false the nearest item is used to determine the index.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'dataset'
}
}
});
```
## x
Returns all items that would intersect based on the `X` coordinate of the position only. Would be useful for a vertical cursor implementation. Note that this only applies to cartesian charts.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'x'
}
}
});
```
## y
Returns all items that would intersect based on the `Y` coordinate of the position. This would be useful for a horizontal cursor implementation. Note that this only applies to cartesian charts.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'y'
}
}
});
```

View File

@@ -0,0 +1,48 @@
# Options
## Scriptable Options
Scriptable options also accept a function which is called for each of the underlying data values and that takes the unique argument `context` representing contextual information (see [option context](options.md#option-context)).
Example:
```javascript
color: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
return value < 0 ? 'red' : // draw negative values in red
index % 2 ? 'blue' : // else, alternate values in blue and green
'green';
}
```
## Indexable Options
Indexable options also accept an array in which each item corresponds to the element at the same index. Note that this method requires to provide as many items as data, so, in most cases, using a [function](#scriptable-options) is more appropriated if supported.
Example:
```javascript
color: [
'red', // color for data at index 0
'blue', // color for data at index 1
'green', // color for data at index 2
'black', // color for data at index 3
//...
]
```
## Option Context
The option context is used to give contextual information when resolving options and currently only applies to [scriptable options](#scriptable-options).
The context object contains the following properties:
- `chart`: the associated chart
- `dataIndex`: index of the current data
- `dataset`: dataset at index `datasetIndex`
- `datasetIndex`: index of the current dataset
- `hover`: true if hovered
**Important**: since the context can represent different types of entities (dataset, data, etc.), some properties may be `undefined` so be sure to test any context property before using it.

View File

@@ -0,0 +1,84 @@
# Performance
Chart.js charts are rendered on `canvas` elements, which makes rendering quite fast. For large datasets or performance sensitive applications, you may wish to consider the tips below.
## Tick Calculation
### Rotation
[Specify a rotation value](https://www.chartjs.org/docs/latest/axes/cartesian/#tick-configuration) by setting `minRotation` and `maxRotation` to the same value, which avoids the chart from having to automatically determine a value to use.
### Sampling
Set the [`ticks.sampleSize`](../axes/cartesian/README.md#tick-configuration) option. This will determine how large your labels are by looking at only a subset of them in order to render axes more quickly. This works best if there is not a large variance in the size of your labels.
## Disable Animations
If your charts have long render times, it is a good idea to disable animations. Doing so will mean that the chart needs to only be rendered once during an update instead of multiple times. This will have the effect of reducing CPU usage and improving general page performance.
To disable animations
```javascript
new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: {
duration: 0 // general animation time
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 0 // animation duration after a resize
}
});
```
## Data Decimation
Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide.
There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks.
## Line Charts
### Disable Bezier Curves
If you are drawing lines on your chart, disabling bezier curves will improve render times since drawing a straight line is more performant than a bezier curve.
To disable bezier curves for an entire chart:
```javascript
new Chart(ctx, {
type: 'line',
data: data,
options: {
elements: {
line: {
tension: 0 // disables bezier curves
}
}
}
});
```
### Disable Line Drawing
If you have a lot of data points, it can be more performant to disable rendering of the line for a dataset and only draw points. Doing this means that there is less to draw on the canvas which will improve render performance.
To disable lines:
```javascript
new Chart(ctx, {
type: 'line',
data: {
datasets: [{
showLine: false // disable for a single dataset
}]
},
options: {
showLines: false // disable for all datasets
}
});
```

View File

@@ -0,0 +1,51 @@
# Responsive Charts
When it comes to changing the chart size based on the window size, a major limitation is that the canvas *render* size (`canvas.width` and `.height`) can **not** be expressed with relative values, contrary to the *display* size (`canvas.style.width` and `.height`). Furthermore, these sizes are independent from each other and thus the canvas *render* size does not adjust automatically based on the *display* size, making the rendering inaccurate.
The following examples **do not work**:
- `<canvas height="40vh" width="80vw">`: **invalid** values, the canvas doesn't resize ([example](https://codepen.io/chartjs/pen/oWLZaR))
- `<canvas style="height:40vh; width:80vw">`: **invalid** behavior, the canvas is resized but becomes blurry ([example](https://codepen.io/chartjs/pen/WjxpmO))
Chart.js provides a [few options](#configuration-options) to enable responsiveness and control the resize behavior of charts by detecting when the canvas *display* size changes and update the *render* size accordingly.
## Configuration Options
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `responsive` | `boolean` | `true` | Resizes the chart canvas when its container does ([important note...](#important-note)).
| `responsiveAnimationDuration` | `number` | `0` | Duration in milliseconds it takes to animate to new size after a resize event.
| `maintainAspectRatio` | `boolean` | `true` | Maintain the original canvas aspect ratio `(width / height)` when resizing.
| `aspectRatio` | `number` | `2` | Canvas aspect ratio (i.e. `width / height`, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style.
| `onResize` | `function` | `null` | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size.
## Important Note
Detecting when the canvas size changes can not be done directly from the `canvas` element. Chart.js uses its parent container to update the canvas *render* and *display* sizes. However, this method requires the container to be **relatively positioned** and **dedicated to the chart canvas only**. Responsiveness can then be achieved by setting relative values for the container size ([example](https://codepen.io/chartjs/pen/YVWZbz)):
```html
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
<canvas id="chart"></canvas>
</div>
```
The chart can also be programmatically resized by modifying the container size:
```javascript
chart.canvas.parentNode.style.height = '128px';
chart.canvas.parentNode.style.width = '128px';
```
Note that in order for the above code to correctly resize the chart height, the [`maintainAspectRatio`](#configuration-options) option must also be set to `false`.
## Printing Resizeable Charts
CSS media queries allow changing styles when printing a page. The CSS applied from these media queries may cause charts to need to resize. However, the resize won't happen automatically. To support resizing charts when printing, one needs to hook the [onbeforeprint](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeprint) event and manually trigger resizing of each chart.
```javascript
function beforePrintHandler () {
for (var id in Chart.instances) {
Chart.instances[id].resize();
}
}
```