upgrade app

This commit is contained in:
Xes
2025-08-14 22:33:03 +02:00
parent d862a535e5
commit 2fe1c43b3e
39284 changed files with 991979 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
{
"name": "chart.js",
"description": "Simple HTML5 charts using the canvas element.",
"homepage": "https://www.chartjs.org",
"license": "MIT",
"version": "2.9.3",
"main": "./dist/Chart.js",
"ignore": [
".github",
".codeclimate.yml",
".gitignore",
".npmignore",
".travis.yml",
"scripts"
],
"_release": "2.9.3",
"_resolution": {
"type": "version",
"tag": "v2.9.3",
"commit": "190a12b31951594f2e45447fc01bf72569f0469f"
},
"_source": "https://github.com/chartjs/Chart.js.git",
"_target": ">= 2.6.0",
"_originalSource": "chart.js"
}

View File

@@ -0,0 +1,18 @@
# https://editorconfig.org
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[gulpfile.js]
indent_style = space
indent_size = 2
[*.yml]
indent_style = space
indent_size = 2

View File

@@ -0,0 +1 @@
**/*{.,-}min.js

View File

@@ -0,0 +1,7 @@
extends: chartjs
env:
browser: true
node: true
plugins: ['html']

View File

@@ -0,0 +1,19 @@
{
"indent-style": "tabs",
"line-end-style": false,
"attr-quote-style": "double",
"spec-char-escape": false,
"attr-bans": [
"align",
"background",
"bgcolor",
"border",
"frameborder",
"longdesc",
"marginwidth",
"marginheight",
"scrolling"
],
"tag-bans": [ "b", "i" ],
"id-class-style": false
}

View File

@@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2018 Chart.js Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,36 @@
# Maintaining
## Release Process
Chart.js relies on [Travis CI](https://travis-ci.org/) to automate the library [releases](https://github.com/chartjs/Chart.js/releases).
### Releasing a New Version
1. draft release notes on [GitHub](https://github.com/chartjs/Chart.js/releases/new) for the upcoming tag
1. update `master` `package.json` version using [semver](https://semver.org/) semantic
1. merge `master` into the `release` branch
1. follow the build process on [Travis CI](https://travis-ci.org/chartjs/Chart.js)
> **Note:** if `master` is merged in `release` with a `package.json` version that already exists, the tag
creation fails and the release process is aborted.
### Automated Tasks
Merging into the `release` branch kicks off the automated release process:
* build of the `dist/*.js` files
* `bower.json` is generated from `package.json`
* `dist/*.js` and `bower.json` are added to a detached branch
* a tag is created from the `package.json` version
* tag (with dist files) is pushed to GitHub
Creation of this tag triggers a new build:
* `Chart.js.zip` package is generated, containing dist files and examples
* `dist/*.js` and `Chart.js.zip` are attached to the GitHub release (downloads)
* a new npm package is published on [npmjs](https://www.npmjs.com/package/chart.js)
Finally, [cdnjs](https://cdnjs.com/libraries/Chart.js) is automatically updated from the npm release.
### Further Reading
* [Travis GitHub releases](https://github.com/chartjs/Chart.js/pull/2555)
* [Bower support and dist/* files](https://github.com/chartjs/Chart.js/issues/3033)
* [cdnjs npm auto update](https://github.com/cdnjs/cdnjs/pull/8401)

View File

@@ -0,0 +1,32 @@
<p align="center">
<img src="https://www.chartjs.org/media/logo-title.svg"><br/>
Simple yet flexible JavaScript charting for designers & developers
</p>
<p align="center">
<a href="https://www.chartjs.org/docs/latest/getting-started/installation.html"><img src="https://img.shields.io/github/release/chartjs/Chart.js.svg?style=flat-square&maxAge=600" alt="Downloads"></a>
<a href="https://travis-ci.org/chartjs/Chart.js"><img src="https://img.shields.io/travis/chartjs/Chart.js.svg?style=flat-square&maxAge=600" alt="Builds"></a>
<a href="https://coveralls.io/github/chartjs/Chart.js?branch=master"><img src="https://img.shields.io/coveralls/chartjs/Chart.js.svg?style=flat-square&maxAge=600" alt="Coverage"></a>
<a href="https://github.com/chartjs/awesome"><img src="https://awesome.re/badge-flat2.svg" alt="Awesome"></a>
<a href="https://chartjs-slack.herokuapp.com/"><img src="https://img.shields.io/badge/slack-chartjs-blue.svg?style=flat-square&maxAge=3600" alt="Slack"></a>
</p>
## Documentation
- [Introduction](https://www.chartjs.org/docs/latest/)
- [Getting Started](https://www.chartjs.org/docs/latest/getting-started/)
- [General](https://www.chartjs.org/docs/latest/general/)
- [Configuration](https://www.chartjs.org/docs/latest/configuration/)
- [Charts](https://www.chartjs.org/docs/latest/charts/)
- [Axes](https://www.chartjs.org/docs/latest/axes/)
- [Developers](https://www.chartjs.org/docs/latest/developers/)
- [Popular Extensions](https://github.com/chartjs/awesome)
- [Samples](https://www.chartjs.org/samples/)
## Contributing
Instructions on building and testing Chart.js can be found in [the documentation](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md#building-and-testing). Before submitting an issue or a pull request, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first. For support, please post questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs) with the `chartjs` tag.
## License
Chart.js is available under the [MIT license](https://opensource.org/licenses/MIT).

View File

@@ -0,0 +1,32 @@
{
"root": "./docs",
"title": "Chart.js documentation",
"author": "chartjs",
"gitbook": "3.2.2",
"plugins": [
"-lunr",
"-search",
"search-plus",
"anchorjs",
"chartjs",
"ga",
"redirect"
],
"pluginsConfig": {
"anchorjs": {
"icon": "#",
"placement": "left",
"visible": "always"
},
"ga": {
"token": "UA-28909194-3",
"configuration": "auto"
},
"theme-default": {
"showLevel": false,
"styles": {
"website": "style.css"
}
}
}
}

View File

@@ -0,0 +1,16 @@
{
"name": "chart.js",
"description": "Simple HTML5 charts using the canvas element.",
"homepage": "https://www.chartjs.org",
"license": "MIT",
"version": "2.9.3",
"main": "./dist/Chart.js",
"ignore": [
".github",
".codeclimate.yml",
".gitignore",
".npmignore",
".travis.yml",
"scripts"
]
}

View File

@@ -0,0 +1,26 @@
{
"name": "nnnick/chartjs",
"type": "library",
"description": "Simple HTML5 charts using the canvas element.",
"keywords": [
"chart",
"js"
],
"homepage": "https://www.chartjs.org/",
"license": "MIT",
"authors": [
{
"name": "NICK DOWNIE",
"email": "hello@nickdownie.com"
}
],
"require": {
"php": ">=5.3.3"
},
"minimum-stability": "stable",
"extra": {
"branch-alias": {
"release/2.0": "v2.0-dev"
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,47 @@
/*
* DOM element rendering detection
* https://davidwalsh.name/detect-node-insertion
*/
@keyframes chartjs-render-animation {
from { opacity: 0.99; }
to { opacity: 1; }
}
.chartjs-render-monitor {
animation: chartjs-render-animation 0.001s;
}
/*
* DOM element resizing detection
* https://github.com/marcj/css-element-queries
*/
.chartjs-size-monitor,
.chartjs-size-monitor-expand,
.chartjs-size-monitor-shrink {
position: absolute;
direction: ltr;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
pointer-events: none;
visibility: hidden;
z-index: -1;
}
.chartjs-size-monitor-expand > div {
position: absolute;
width: 1000000px;
height: 1000000px;
left: 0;
top: 0;
}
.chartjs-size-monitor-shrink > div {
position: absolute;
width: 200%;
height: 200%;
left: 0;
top: 0;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
@keyframes chartjs-render-animation{from{opacity:.99}to{opacity:1}}.chartjs-render-monitor{animation:chartjs-render-animation 1ms}.chartjs-size-monitor,.chartjs-size-monitor-expand,.chartjs-size-monitor-shrink{position:absolute;direction:ltr;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1}.chartjs-size-monitor-expand>div{position:absolute;width:1000000px;height:1000000px;left:0;top:0}.chartjs-size-monitor-shrink>div{position:absolute;width:200%;height:200%;left:0;top:0}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,65 @@
# Chart.js
[![slack](https://img.shields.io/badge/slack-chartjs-blue.svg?style=flat-square&maxAge=3600)](https://chartjs-slack.herokuapp.com/)
## Installation
You can download the latest version of Chart.js from the [GitHub releases](https://github.com/chartjs/Chart.js/releases/latest) or use a [Chart.js CDN](https://www.jsdelivr.com/package/npm/chart.js). Detailed installation instructions can be found on the [installation](./getting-started/installation.md) page.
## Creating a Chart
It's easy to get started with Chart.js. All that's required is the script included in your page along with a single `<canvas>` node to render the chart.
In this example, we create a bar chart for a single dataset and render that in our page. You can see all the ways to use Chart.js in the [usage documentation](./getting-started/usage.md).
```html
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
```
## Contributing
Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first.
For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs).
## License
Chart.js is available under the [MIT license](https://opensource.org/licenses/MIT).

View File

@@ -0,0 +1,57 @@
# Summary
* [Chart.js](https://www.chartjs.org)
* [Introduction](README.md)
* [Getting Started](getting-started/README.md)
* [Installation](getting-started/installation.md)
* [Integration](getting-started/integration.md)
* [Usage](getting-started/usage.md)
* [General](general/README.md)
* [Accessibility](general/accessibility.md)
* [Responsive](general/responsive.md)
* [Pixel Ratio](general/device-pixel-ratio.md)
* [Interactions](general/interactions/README.md)
* [Events](general/interactions/events.md)
* [Modes](general/interactions/modes.md)
* [Options](general/options.md)
* [Colors](general/colors.md)
* [Fonts](general/fonts.md)
* [Performance](general/performance.md)
* [Configuration](configuration/README.md)
* [Animations](configuration/animations.md)
* [Layout](configuration/layout.md)
* [Legend](configuration/legend.md)
* [Title](configuration/title.md)
* [Tooltip](configuration/tooltip.md)
* [Elements](configuration/elements.md)
* [Charts](charts/README.md)
* [Line](charts/line.md)
* [Bar](charts/bar.md)
* [Radar](charts/radar.md)
* [Doughnut & Pie](charts/doughnut.md)
* [Polar Area](charts/polar.md)
* [Bubble](charts/bubble.md)
* [Scatter](charts/scatter.md)
* [Area](charts/area.md)
* [Mixed](charts/mixed.md)
* [Axes](axes/README.md)
* [Cartesian](axes/cartesian/README.md)
* [Category](axes/cartesian/category.md)
* [Linear](axes/cartesian/linear.md)
* [Logarithmic](axes/cartesian/logarithmic.md)
* [Time](axes/cartesian/time.md)
* [Radial](axes/radial/README.md)
* [Linear](axes/radial/linear.md)
* [Labelling](axes/labelling.md)
* [Styling](axes/styling.md)
* [Developers](developers/README.md)
* [Chart.js API](developers/api.md)
* [Updating Charts](developers/updates.md)
* [Plugins](developers/plugins.md)
* [New Charts](developers/charts.md)
* [New Axes](developers/axes.md)
* [Contributing](developers/contributing.md)
* [Additional Notes](notes/README.md)
* [Comparison Table](notes/comparison.md)
* [Popular Extensions](notes/extensions.md)
* [License](notes/license.md)

View File

@@ -0,0 +1,58 @@
# Axes
Axes are an integral part of a chart. They are used to determine how data maps to a pixel value on the chart. In a cartesian chart, there is 1 or more X axis and 1 or more Y axis to map points onto the 2 dimensional canvas. These axes are know as ['cartesian axes'](./cartesian/README.md#cartesian-axes).
In a radial chart, such as a radar chart or a polar area chart, there is a single axis that maps points in the angular and radial directions. These are known as ['radial axes'](./radial/README.md#radial-axes).
Scales in Chart.js >v2.0 are significantly more powerful, but also different than those of v1.0.
* Multiple X & Y axes are supported.
* A built-in label auto-skip feature detects would-be overlapping ticks and labels and removes every nth label to keep things displaying normally.
* Scale titles are supported.
* New scale types can be extended without writing an entirely new chart type.
## Common Configuration
The following properties are common to all axes provided by Chart.js.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | <code>boolean&#124;string</code> | `true` | Controls the axis global visibility (visible when `true`, hidden when `false`). When `display: 'auto'`, the axis is visible only if at least one associated dataset is visible.
| `callbacks` | `object` | | Callback functions to hook into the axis lifecycle. [more...](#callbacks)
| `weight` | `number` | `0` | The weight used to sort the axis. Higher weights are further away from the chart area.
### Callbacks
There are a number of config callbacks that can be used to change parameters in the scale at different points in the update process.
| Name | Arguments | Description
| ---- | --------- | -----------
| `beforeUpdate` | `axis` | Callback called before the update process starts.
| `beforeSetDimensions` | `axis` | Callback that runs before dimensions are set.
| `afterSetDimensions` | `axis` | Callback that runs after dimensions are set.
| `beforeDataLimits` | `axis` | Callback that runs before data limits are determined.
| `afterDataLimits` | `axis` | Callback that runs after data limits are determined.
| `beforeBuildTicks` | `axis` | Callback that runs before ticks are created.
| `afterBuildTicks` | `axis`, `ticks` | Callback that runs after ticks are created. Useful for filtering ticks. Should return the filtered ticks.
| `beforeTickToLabelConversion` | `axis` | Callback that runs before ticks are converted into strings.
| `afterTickToLabelConversion` | `axis` | Callback that runs after ticks are converted into strings.
| `beforeCalculateTickRotation` | `axis` | Callback that runs before tick rotation is determined.
| `afterCalculateTickRotation` | `axis` | Callback that runs after tick rotation is determined.
| `beforeFit` | `axis` | Callback that runs before the scale fits to the canvas.
| `afterFit` | `axis` | Callback that runs after the scale fits to the canvas.
| `afterUpdate` | `axis` | Callback that runs at the end of the update process.
### Updating Axis Defaults
The default configuration for a scale can be easily changed using the scale service. All you need to do is to pass in a partial configuration that will be merged with the current scale default configuration to form the new default.
For example, to set the minimum value of 0 for all linear scales, you would do the following. Any linear scales created after this time would now have a minimum of 0.
```javascript
Chart.scaleService.updateScaleDefaults('linear', {
ticks: {
min: 0
}
});
```
## Creating New Axes
To create a new axis, see the [developer docs](../developers/axes.md).

View File

@@ -0,0 +1,108 @@
# Cartesian Axes
Axes that follow a cartesian grid are known as 'Cartesian Axes'. Cartesian axes are used for line, bar, and bubble charts. Four cartesian axes are included in Chart.js by default.
* [linear](./linear.md#linear-cartesian-axis)
* [logarithmic](./logarithmic.md#logarithmic-cartesian-axis)
* [category](./category.md#category-cartesian-axis)
* [time](./time.md#time-cartesian-axis)
## Common Configuration
All of the included cartesian axes support a number of common options.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `type` | `string` | | Type of scale being employed. Custom scales can be created and registered with a string key. This allows changing the type of an axis for a chart.
| `position` | `string` | | Position of the axis in the chart. Possible values are: `'top'`, `'left'`, `'bottom'`, `'right'`
| `offset` | `boolean` | `false` | If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to `true` for a bar chart by default.
| `id` | `string` | | The ID is used to link datasets and scale axes together. [more...](#axis-id)
| `gridLines` | `object` | | Grid line configuration. [more...](../styling.md#grid-line-configuration)
| `scaleLabel` | `object` | | Scale title configuration. [more...](../labelling.md#scale-title-configuration)
| `ticks` | `object` | | Tick configuration. [more...](#tick-configuration)
### Tick Configuration
The following options are common to all cartesian axes but do not apply to other axes.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `min` | `number` | | User defined minimum value for the scale, overrides minimum value from data.
| `max` | `number` | | User defined maximum value for the scale, overrides maximum value from data.
| `sampleSize` | `number` | `ticks.length` | The number of ticks to examine when deciding how many labels will fit. Setting a smaller value will be faster, but may be less accurate when there is large variability in label length.
| `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what.
| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled.
| `labelOffset` | `number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas*
| `maxRotation` | `number` | `50` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.*
| `minRotation` | `number` | `0` | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.*
| `mirror` | `boolean` | `false` | Flips tick labels around axis, displaying the labels inside the chart instead of outside. *Note: Only applicable to vertical scales.*
| `padding` | `number` | `0` | Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction.
### Axis ID
The properties `dataset.xAxisID` or `dataset.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used.
```javascript
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
// This dataset appears on the first axis
yAxisID: 'first-y-axis'
}, {
// This dataset appears on the second axis
yAxisID: 'second-y-axis'
}]
},
options: {
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear'
}, {
id: 'second-y-axis',
type: 'linear'
}]
}
}
});
```
## Creating Multiple Axes
With cartesian axes, it is possible to create multiple X and Y axes. To do so, you can add multiple configuration objects to the `xAxes` and `yAxes` properties. When adding new axes, it is important to ensure that you specify the type of the new axes as default types are **not** used in this case.
In the example below, we are creating two Y axes. We then use the `yAxisID` property to map the datasets to their correct axes.
```javascript
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [20, 50, 100, 75, 25, 0],
label: 'Left dataset',
// This binds the dataset to the left y axis
yAxisID: 'left-y-axis'
}, {
data: [0.1, 0.5, 1.0, 2.0, 1.5, 0],
label: 'Right dataset',
// This binds the dataset to the right y axis
yAxisID: 'right-y-axis'
}],
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
},
options: {
scales: {
yAxes: [{
id: 'left-y-axis',
type: 'linear',
position: 'left'
}, {
id: 'right-y-axis',
type: 'linear',
position: 'right'
}]
}
}
});
```

View File

@@ -0,0 +1,69 @@
# Category Cartesian Axis
If global configuration is used, labels are drawn from one of the label arrays included in the chart data. If only `data.labels` is defined, this will be used. If `data.xLabels` is defined and the axis is horizontal, this will be used. Similarly, if `data.yLabels` is defined and the axis is vertical, this property will be used. Using both `xLabels` and `yLabels` together can create a chart that uses strings for both the X and Y axes.
Specifying any of the settings above defines the x axis as `type: 'category'` if not defined otherwise. For more fine-grained control of category labels it is also possible to add `labels` as part of the category axis definition. Doing so does not apply the global defaults.
## Category Axis Definition
Globally:
```javascript
let chart = new Chart(ctx, {
type: ...
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: ...
}
});
```
As part of axis definition:
```javascript
let chart = new Chart(ctx, {
type: ...
data: ...
options: {
scales: {
xAxes: [{
type: 'category',
labels: ['January', 'February', 'March', 'April', 'May', 'June']
}]
}
}
});
```
## Tick Configuration Options
The category scale provides the following options for configuring tick marks. They are nested in the `ticks` sub object. These options extend the [common tick configuration](README.md#tick-configuration).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `labels` | `string[]` | - | An array of labels to display.
| `min` | `string` | | The minimum item to display. [more...](#min-max-configuration)
| `max` | `string` | | The maximum item to display. [more...](#min-max-configuration)
## Min Max Configuration
For both the `min` and `max` properties, the value must be in the `labels` array. In the example below, the x axis would only display "March" through "June".
```javascript
let chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [10, 20, 30, 40, 50, 60]
}],
labels: ['January', 'February', 'March', 'April', 'May', 'June']
},
options: {
scales: {
xAxes: [{
ticks: {
min: 'March'
}
}]
}
}
});
```

View File

@@ -0,0 +1,73 @@
# Linear Cartesian Axis
The linear scale is use to chart numerical data. It can be placed on either the x or y axis. The scatter chart type automatically configures a line chart to use one of these scales for the x axis. As the name suggests, linear interpolation is used to determine where a value lies on the axis.
## Tick Configuration Options
The following options are provided by the linear scale. They are all located in the `ticks` sub options. These options extend the [common tick configuration](README.md#tick-configuration).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `beginAtZero` | `boolean` | | if true, scale will include 0 if it is not already included.
| `maxTicksLimit` | `number` | `11` | Maximum number of ticks and gridlines to show.
| `precision` | `number` | | if defined and `stepSize` is not specified, the step size will be rounded to this many decimal places.
| `stepSize` | `number` | | User defined fixed step size for the scale. [more...](#step-size)
| `suggestedMax` | `number` | | Adjustment used when calculating the maximum data value. [more...](#axis-range-settings)
| `suggestedMin` | `number` | | Adjustment used when calculating the minimum data value. [more...](#axis-range-settings)
## Axis Range Settings
Given the number of axis range settings, it is important to understand how they all interact with each other.
The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour.
```javascript
let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin);
let maxDataValue = Math.max(mostPositiveValue, options.ticks.suggestedMax);
```
In this example, the largest positive value is 50, but the data maximum is expanded out to 100. However, because the lowest data value is below the `suggestedMin` setting, it is ignored.
```javascript
let chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'First dataset',
data: [0, 20, 40, 50]
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: 50,
suggestedMax: 100
}
}]
}
}
});
```
In contrast to the `suggested*` settings, the `min` and `max` settings set explicit ends to the axes. When these are set, some data points may not be visible.
## Step Size
If set, the scale ticks will be enumerated by multiple of `stepSize`, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm.
This example sets up a chart with a y axis that creates ticks at `0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5`.
```javascript
let options = {
scales: {
yAxes: [{
ticks: {
max: 5,
min: 0,
stepSize: 0.5
}
}]
}
};
```

View File

@@ -0,0 +1,7 @@
# Logarithmic Cartesian Axis
The logarithmic scale is use to chart numerical data. It can be placed on either the x or y axis. As the name suggests, logarithmic interpolation is used to determine where a value lies on the axis.
## Tick Configuration Options
The logarithmic scale options extend the [common tick configuration](README.md#tick-configuration). This scale does not define any options that are unique to it.

View File

@@ -0,0 +1,157 @@
# Time Cartesian Axis
The time scale is used to display times and dates. When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.
## Date Adapters
The time scale requires both a date library and corresponding adapter to be present. By default, Chart.js includes an adapter for Moment.js. You may wish to [exclude moment](../../getting-started/integration.md) and choose from [other available adapters](https://github.com/chartjs/awesome#adapters) instead.
## Data Sets
### Input Data
The x-axis data points may additionally be specified via the `t` or `x` attribute when using the time scale.
```javascript
data: [{
x: new Date(),
y: 1
}, {
t: new Date(),
y: 10
}]
```
### Date Formats
When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See [Moment.js docs](https://momentjs.com/docs/#/parsing/) for details.
## Configuration Options
The following options are provided by the time scale. You may also set options provided by the [common tick configuration](README.md#tick-configuration).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `adapters.date` | `object` | `{}` | Options for adapter for external date library if that adapter needs or supports options
| `distribution` | `string` | `'linear'` | How data is plotted. [more...](#scale-distribution)
| `bounds` | `string` | `'data'` | Determines the scale bounds. [more...](#scale-bounds)
| `ticks.source` | `string` | `'auto'` | How ticks are generated. [more...](#ticks-source)
| `time.displayFormats` | `object` | | Sets how different time units are displayed. [more...](#display-formats)
| `time.isoWeekday` | `boolean` | `false` | If true and the unit is set to 'week', then the first day of the week will be Monday. Otherwise, it will be Sunday.
| `time.parser` | <code>string&#124;function</code> | | Custom parser for dates. [more...](#parser)
| `time.round` | `string` | `false` | If defined, dates will be rounded to the start of this unit. See [Time Units](#time-units) below for the allowed units.
| `time.tooltipFormat` | `string` | | The Moment.js format string to use for the tooltip.
| `time.unit` | `string` | `false` | If defined, will force the unit to be a certain type. See [Time Units](#time-units) section below for details.
| `time.stepSize` | `number` | `1` | The number of units between grid lines.
| `time.minUnit` | `string` | `'millisecond'` | The minimum display format to be used for a time unit.
### Time Units
The following time measurements are supported. The names can be passed as strings to the `time.unit` config option to force a certain unit.
* `'millisecond'`
* `'second'`
* `'minute'`
* `'hour'`
* `'day'`
* `'week'`
* `'month'`
* `'quarter'`
* `'year'`
For example, to create a chart with a time scale that always displayed units per month, the following config could be used.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month'
}
}]
}
}
});
```
### Display Formats
The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [Moment.js](https://momentjs.com/docs/#/displaying/format/) for the allowable format strings.
Name | Default | Example
--- | --- | ---
`millisecond` | `'h:mm:ss.SSS a'` | `'11:20:01.123 AM'`
`second` | `'h:mm:ss a'` | `'11:20:01 AM'`
`minute` | `'h:mm a'` | `'11:20 AM'`
`hour` | `'hA'` | `'11AM'`
`day` | `'MMM D'` | `'Sep 4'`
`week` | `'ll'` | `'Sep 4 2015'`
`month` | `'MMM YYYY'` | `'Sep 2015'`
`quarter` | `'[Q]Q - YYYY'` | `'Q3 - 2015'`
`year` | `'YYYY'` | `'2015'`
For example, to set the display format for the `quarter` unit to show the month and year, the following config would be passed to the chart constructor.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'MMM YYYY'
}
}
}]
}
}
});
```
### Scale Distribution
The `distribution` property controls the data distribution along the scale:
* `'linear'`: data are spread according to their time (distances can vary)
* `'series'`: data are spread at the same distance from each other
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'series'
}]
}
}
});
```
### Scale Bounds
The `bounds` property controls the scale boundary strategy (bypassed by `min`/`max` time options).
* `'data'`: makes sure data are fully visible, labels outside are removed
* `'ticks'`: makes sure ticks are fully visible, data outside are truncated
### Ticks Source
The `ticks.source` property controls the ticks generation.
* `'auto'`: generates "optimal" ticks based on scale size and time options
* `'data'`: generates ticks from data (including labels from data `{t|x|y}` objects)
* `'labels'`: generates ticks from user given `labels` ONLY
### Parser
If this property is defined as a string, it is interpreted as a custom format to be used by Moment.js to parse the date.
If this is a function, it must return a Moment.js object given the appropriate data value.

View File

@@ -0,0 +1,46 @@
# Labeling Axes
When creating a chart, you want to tell the viewer what data they are viewing. To do this, you need to label the axis.
## Scale Title Configuration
The scale label configuration is nested under the scale configuration in the `scaleLabel` key. It defines options for the scale title. Note that this only applies to cartesian axes.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `false` | If true, display the axis title.
| `labelString` | `string` | `''` | The text for the title. (i.e. "# of People" or "Response Choices").
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).
| `fontColor` | `Color` | `'#666'` | Font color for scale title.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the scale title, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for scale title.
| `fontStyle` | `string` | `'normal'` | Font style for the scale title, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `padding` | <code>number&#124;object</code> | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented.
## Creating Custom Tick Formats
It is also common to want to change the tick marks to include information about the data type. For example, adding a dollar sign ('$'). To do this, you need to override the `ticks.callback` method in the axis configuration.
In the following example, every label of the Y axis would be displayed with a dollar sign at the front.
If the callback returns `null` or `undefined` the associated grid line will be hidden.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return '$' + value;
}
}
}]
}
}
});
```
The third parameter passed to the callback function is an array of labels, but in the time scale, it is an array of `{label: string, major: boolean}` objects.

View File

@@ -0,0 +1,5 @@
# Radial Axes
Radial axes are used specifically for the radar and polar area chart types. These axes overlay the chart area, rather than being positioned on one of the edges. One radial axis is included by default in Chart.js.
* [linear](./linear.md#linear-radial-axis)

View File

@@ -0,0 +1,113 @@
# Linear Radial Axis
The linear scale is used to chart numerical data. As the name suggests, linear interpolation is used to determine where a value lies in relation the center of the axis.
The following additional configuration options are provided by the radial linear scale.
## Configuration Options
The axis has configuration properties for ticks, angle lines (line that appear in a radar chart outward from the center), pointLabels (labels around the edge in a radar chart). The following sections define each of the properties in those sections.
| Name | Type | Description
| ---- | ---- | -----------
| `angleLines` | `object` | Angle line configuration. [more...](#angle-line-options)
| `gridLines` | `object` | Grid line configuration. [more...](../styling.md#grid-line-configuration)
| `pointLabels` | `object` | Point label configuration. [more...](#point-label-options)
| `ticks` | `object` | Tick configuration. [more...](#tick-options)
## Tick Options
The following options are provided by the linear scale. They are all located in the `ticks` sub options. The [common tick configuration](../styling.md#tick-configuration) options are supported by this axis.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `backdropColor` | `Color` | `'rgba(255, 255, 255, 0.75)'` | Color of label backdrops.
| `backdropPaddingX` | `number` | `2` | Horizontal padding of label backdrop.
| `backdropPaddingY` | `number` | `2` | Vertical padding of label backdrop.
| `beginAtZero` | `boolean` | `false` | if true, scale will include 0 if it is not already included.
| `min` | `number` | | User defined minimum number for the scale, overrides minimum value from data. [more...](#axis-range-settings)
| `max` | `number` | | User defined maximum number for the scale, overrides maximum value from data. [more...](#axis-range-settings)
| `maxTicksLimit` | `number` | `11` | Maximum number of ticks and gridlines to show.
| `precision` | `number` | | if defined and `stepSize` is not specified, the step size will be rounded to this many decimal places.
| `stepSize` | `number` | | User defined fixed step size for the scale. [more...](#step-size)
| `suggestedMax` | `number` | | Adjustment used when calculating the maximum data value. [more...](#axis-range-settings)
| `suggestedMin` | `number` | | Adjustment used when calculating the minimum data value. [more...](#axis-range-settings)
| `showLabelBackdrop` | `boolean` | `true` | If true, draw a background behind the tick labels.
## Axis Range Settings
Given the number of axis range settings, it is important to understand how they all interact with each other.
The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour.
```javascript
let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin);
let maxDataValue = Math.max(mostPositiveValue, options.ticks.suggestedMax);
```
In this example, the largest positive value is 50, but the data maximum is expanded out to 100. However, because the lowest data value is below the `suggestedMin` setting, it is ignored.
```javascript
let chart = new Chart(ctx, {
type: 'radar',
data: {
datasets: [{
label: 'First dataset',
data: [0, 20, 40, 50]
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scale: {
ticks: {
suggestedMin: 50,
suggestedMax: 100
}
}
}
});
```
In contrast to the `suggested*` settings, the `min` and `max` settings set explicit ends to the axes. When these are set, some data points may not be visible.
## Step Size
If set, the scale ticks will be enumerated by multiple of `stepSize`, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm.
This example sets up a chart with a y axis that creates ticks at `0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5`.
```javascript
let options = {
scale: {
ticks: {
max: 5,
min: 0,
stepSize: 0.5
}
}
};
```
## Angle Line Options
The following options are used to configure angled lines that radiate from the center of the chart to the point labels. They can be found in the `angleLines` sub options.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `true` | if true, angle lines are shown.
| `color` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Color of angled lines.
| `lineWidth` | `number` | `1` | Width of angled lines.
| `borderDash` | `number[]` | `[]` | Length and spacing of dashes on angled lines. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | `number` | `0.0` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
## Point Label Options
The following options are used to configure the point labels that are shown on the perimeter of the scale. They can be found in the `pointLabels` sub options.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `true` | if true, point labels are shown.
| `callback` | `function` | | Callback function to transform data labels to point labels. The default implementation simply returns the current string.
| `fontColor` | <code>Color&#124;Color[]</code> | `'#666'` | Font color for point labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family to use when rendering labels.
| `fontSize` | `number` | `10` | font size in pixels.
| `fontStyle` | `string` | `'normal'` | Font style to use when rendering point labels.
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).

View File

@@ -0,0 +1,69 @@
# Styling
There are a number of options to allow styling an axis. There are settings to control [grid lines](#grid-line-configuration) and [ticks](#tick-configuration).
## Grid Line Configuration
The grid line configuration is nested under the scale configuration in the `gridLines` key. It defines options for the grid lines that run perpendicular to the axis.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `true` | If false, do not display grid lines for this axis.
| `circular` | `boolean` | `false` | If true, gridlines are circular (on radar chart only).
| `color` | <code>Color&#124;Color[]</code> | `'rgba(0, 0, 0, 0.1)'` | The color of the grid lines. If specified as an array, the first color applies to the first grid line, the second to the second grid line and so on.
| `borderDash` | `number[]` | `[]` | Length and spacing of dashes on grid lines. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | `number` | `0.0` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `lineWidth` | <code>number&#124;number[]</code> | `1` | Stroke width of grid lines.
| `drawBorder` | `boolean` | `true` | If true, draw border at the edge between the axis and the chart area.
| `drawOnChartArea` | `boolean` | `true` | If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn.
| `drawTicks` | `boolean` | `true` | If true, draw lines beside the ticks in the axis area beside the chart.
| `tickMarkLength` | `number` | `10` | Length in pixels that the grid lines will draw into the axis area.
| `zeroLineWidth` | `number` | `1` | Stroke width of the grid line for the first index (index 0).
| `zeroLineColor` | `Color` | `'rgba(0, 0, 0, 0.25)'` | Stroke color of the grid line for the first index (index 0).
| `zeroLineBorderDash` | `number[]` | `[]` | Length and spacing of dashes of the grid line for the first index (index 0). See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `zeroLineBorderDashOffset` | `number` | `0.0` | Offset for line dashes of the grid line for the first index (index 0). See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `offsetGridLines` | `boolean` | `false` | If true, grid lines will be shifted to be between labels. This is set to `true` for a bar chart by default.
| `z` | `number` | `0` | z-index of gridline layer. Values &lt;= 0 are drawn under datasets, &gt; 0 on top.
## Tick Configuration
The tick configuration is nested under the scale configuration in the `ticks` key. It defines options for the tick marks that are generated by the axis.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `callback` | `function` | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats).
| `display` | `boolean` | `true` | If true, show tick labels.
| `fontColor` | `Color` | `'#666'` | Font color for tick labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the tick labels, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for the tick labels.
| `fontStyle` | `string` | `'normal'` | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).
| `reverse` | `boolean` | `false` | Reverses order of tick labels.
| `minor` | `object` | `{}` | Minor ticks configuration. Omitted options are inherited from options above.
| `major` | `object` | `{}` | Major ticks configuration. Omitted options are inherited from options above.
| `padding` | `number` | `0` | Sets the offset of the tick labels from the axis
| `z` | `number` | `0` | z-index of tick layer. Useful when ticks are drawn on chart area. Values &lt;= 0 are drawn under datasets, &gt; 0 on top.
## Minor Tick Configuration
The minorTick configuration is nested under the ticks configuration in the `minor` key. It defines options for the minor tick marks that are generated by the axis. Omitted options are inherited from `ticks` configuration.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `callback` | `function` | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats).
| `fontColor` | `Color` | `'#666'` | Font color for tick labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the tick labels, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for the tick labels.
| `fontStyle` | `string` | `'normal'` | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).
## Major Tick Configuration
The majorTick configuration is nested under the ticks configuration in the `major` key. It defines options for the major tick marks that are generated by the axis. Omitted options are inherited from `ticks` configuration. These options are disabled by default.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `enabled` | `boolean` | `false` | If true, major tick options are used to show major ticks.
| `callback` | `function` | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats).
| `fontColor` | `Color` | `'#666'` | Font color for tick labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the tick labels, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for the tick labels.
| `fontStyle` | `string` | `'normal'` | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).

View File

@@ -0,0 +1,14 @@
# Charts
Chart.js comes with built-in chart types:
* [line](./line.md)
* [bar](./bar.md)
* [radar](./radar.md)
* [doughnut and pie](./doughnut.md)
* [polar area](./polar.md)
* [bubble](./bubble.md)
* [scatter](./scatter.md)
[Area charts](area.md) can be built from a line or radar chart using the dataset `fill` option.
To create a new chart type, see the [developer notes](../developers/charts.md#new-charts).

View File

@@ -0,0 +1,72 @@
# Area Charts
Both [line](line.md) and [radar](radar.md) charts support a `fill` option on the dataset object which can be used to create area between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start` or `end` (see [filling modes](#filling-modes)).
> **Note:** this feature is implemented by the [`filler` plugin](https://github.com/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js).
## Filling modes
| Mode | Type | Values |
| :--- | :--- | :--- |
| Absolute dataset index <sup>1</sup> | `number` | `1`, `2`, `3`, ... |
| Relative dataset index <sup>1</sup> | `string` | `'-1'`, `'-2'`, `'+1'`, ... |
| Boundary <sup>2</sup> | `string` | `'start'`, `'end'`, `'origin'` |
| Disabled <sup>3</sup> | `boolean` | `false` |
> <sup>1</sup> dataset filling modes have been introduced in version 2.6.0<br>
> <sup>2</sup> prior version 2.6.0, boundary values was `'zero'`, `'top'`, `'bottom'` (deprecated)<br>
> <sup>3</sup> for backward compatibility, `fill: true` (default) is equivalent to `fill: 'origin'`<br>
**Example**
```javascript
new Chart(ctx, {
data: {
datasets: [
{fill: 'origin'}, // 0: fill to 'origin'
{fill: '+2'}, // 1: fill to dataset 3
{fill: 1}, // 2: fill to dataset 1
{fill: false}, // 3: no fill
{fill: '-2'} // 4: fill to dataset 2
]
}
});
```
## Configuration
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| [`plugins.filler.propagate`](#propagate) | `boolean` | `true` | Fill propagation when target is hidden.
### propagate
`propagate` takes a `boolean` value (default: `true`).
If `true`, the fill area will be recursively extended to the visible target defined by the `fill` value of hidden dataset targets:
**Example**
```javascript
new Chart(ctx, {
data: {
datasets: [
{fill: 'origin'}, // 0: fill to 'origin'
{fill: '-1'}, // 1: fill to dataset 0
{fill: 1}, // 2: fill to dataset 1
{fill: false}, // 3: no fill
{fill: '-2'} // 4: fill to dataset 2
]
},
options: {
plugins: {
filler: {
propagate: true
}
}
}
});
```
`propagate: true`:
- if dataset 2 is hidden, dataset 4 will fill to dataset 1
- if dataset 2 and 1 are hidden, dataset 4 will fill to `'origin'`
`propagate: false`:
- if dataset 2 and/or 4 are hidden, dataset 4 will not be filled

View File

@@ -0,0 +1,323 @@
# Bar
A bar chart provides a way of showing data values represented as vertical bars. It is sometimes used to show trend data, and the comparison of multiple data sets side by side.
{% chartjs %}
{
"type": "bar",
"data": {
"labels": [
"January",
"February",
"March",
"April",
"May",
"June",
"July"
],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 80, 81, 56, 55, 40],
"fill": false,
"backgroundColor": [
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)"
],
"borderColor": [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)"
],
"borderWidth": 1
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
}
{% endchartjs %}
## Example Usage
```javascript
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
```
## Dataset Properties
The bar chart allows a number of properties to be specified for each dataset.
These are used to set display properties for a specific dataset. For example,
the color of the bars is generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderSkipped`](#borderskipped) | `string` | Yes | Yes | `'bottom'`
| [`borderWidth`](#borderwidth) | <code>number&#124;object</code> | Yes | Yes | `0`
| [`data`](#data-structure) | `object[]` | - | - | **required**
| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | - | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | - | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | - | Yes | `1`
| [`label`](#general) | `string` | - | - | `''`
| [`order`](#general) | `number` | - | - | `0`
| [`xAxisID`](#general) | `string` | - | - | first x axis
| [`yAxisID`](#general) | `string` | - | - | first y axis
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
| `xAxisID` | The ID of the x axis to plot this dataset on.
| `yAxisID` | The ID of the y axis to plot this dataset on.
### Styling
The style of each bar can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | The bar background color.
| `borderColor` | The bar border color.
| [`borderSkipped`](#borderskipped) | The edge to skip when drawing bar.
| [`borderWidth`](#borderwidth) | The bar border width (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.rectangle.*`](../configuration/elements.md#rectangle-configuration) options.
#### borderSkipped
This setting is used to avoid drawing the bar stroke at the base of the fill.
In general, this does not need to be changed except when creating chart types
that derive from a bar chart.
**Note:** for negative bars in vertical chart, `top` and `bottom` are flipped. Same goes for `left` and `right` in horizontal chart.
Options are:
* `'bottom'`
* `'left'`
* `'top'`
* `'right'`
* `false`
#### borderWidth
If this value is a number, it is applied to all sides of the rectangle (left, top, right, bottom), except [`borderSkipped`](#borderskipped). If this value is an object, the `left` property defines the left border width. Similarly the `right`, `top` and `bottom` properties can also be specified. Omitted borders and [`borderSkipped`](#borderskipped) are skipped.
### Interactions
The interaction with each bar can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | The bar background color when hovered.
| `hoverBorderColor` | The bar border color when hovered.
| `hoverBorderWidth` | The bar border width when hovered (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.rectangle.*`](../configuration/elements.md#rectangle-configuration) options.
## Dataset Configuration
The bar chart accepts the following configuration from the associated dataset options:
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `barPercentage` | `number` | `0.9` | Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other. [more...](#barpercentage-vs-categorypercentage)
| `categoryPercentage` | `number` | `0.8` | Percent (0-1) of the available width each category should be within the sample width. [more...](#barpercentage-vs-categorypercentage)
| `barThickness` | <code>number&#124;string</code> | | Manually set width of each bar in pixels. If set to `'flex'`, it computes "optimal" sample widths that globally arrange bars side by side. If not set (default), bars are equally sized based on the smallest interval. [more...](#barthickness)
| `maxBarThickness` | `number` | | Set this to ensure that bars are not sized thicker than this.
| `minBarLength` | `number` | | Set this to ensure that bars have a minimum length in pixels.
### Example Usage
```javascript
data: {
datasets: [{
barPercentage: 0.5,
barThickness: 6,
maxBarThickness: 8,
minBarLength: 2,
data: [10, 20, 30, 40, 50, 60, 70]
}]
};
```
### barThickness
If this value is a number, it is applied to the width of each bar, in pixels. When this is enforced, `barPercentage` and `categoryPercentage` are ignored.
If set to `'flex'`, the base sample widths are calculated automatically based on the previous and following samples so that they take the full available widths without overlap. Then, bars are sized using `barPercentage` and `categoryPercentage`. There is no gap when the percentage options are 1. This mode generates bars with different widths when data are not evenly spaced.
If not set (default), the base sample widths are calculated using the smallest interval that prevents bar overlapping, and bars are sized using `barPercentage` and `categoryPercentage`. This mode always generates bars equally sized.
## Scale Configuration
The bar chart sets unique default values for the following configuration from the associated `scale` options:
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `offset` | `boolean` | `true` | If true, extra space is added to the both edges and the axis is scaled to fit into the chart area.
| `gridLines.offsetGridLines` | `boolean` | `true` | If true, the bars for a particular data point fall between the grid lines. The grid line will move to the left by one half of the tick interval. If false, the grid line will go right down the middle of the bars. [more...](#offsetgridlines)
### Example Usage
```javascript
options = {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true
}
}]
}
};
```
### offsetGridLines
If true, the bars for a particular data point fall between the grid lines. The grid line will move to the left by one half of the tick interval, which is the space between the grid lines. If false, the grid line will go right down the middle of the bars. This is set to true for a category scale in a bar chart while false for other scales or chart types by default.
## Default Options
It is common to want to apply a configuration setting to all created bar charts. The global bar chart settings are stored in `Chart.defaults.bar`. Changing the global options only affects charts created after the change. Existing charts are not changed.
## barPercentage vs categoryPercentage
The following shows the relationship between the bar percentage option and the category percentage option.
```text
// categoryPercentage: 1.0
// barPercentage: 1.0
Bar: | 1.0 | 1.0 |
Category: | 1.0 |
Sample: |===========|
// categoryPercentage: 1.0
// barPercentage: 0.5
Bar: |.5| |.5|
Category: | 1.0 |
Sample: |==============|
// categoryPercentage: 0.5
// barPercentage: 1.0
Bar: |1.||1.|
Category: | .5 |
Sample: |==============|
```
## Data Structure
The `data` property of a dataset for a bar chart is specified as an array of numbers. Each point in the data array corresponds to the label at the same index on the x axis.
```javascript
data: [20, 10]
```
You can also specify the dataset as x/y coordinates when using the [time scale](../axes/cartesian/time.md#time-cartesian-axis).
```javascript
data: [{x:'2016-12-25', y:20}, {x:'2016-12-26', y:10}]
```
You can also specify the dataset for a bar chart as arrays of two numbers. This will force rendering of bars with gaps between them (floating-bars). First and second numbers in array will correspond the start and the end point of a bar respectively.
```javascript
data: [[5,6], [-3,-6]]
```
## Stacked Bar Chart
Bar charts can be configured into stacked bar charts by changing the settings on the X and Y axes to enable stacking. Stacked bar charts can be used to show how one data series is made up of a number of smaller pieces.
```javascript
var stackedBar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
```
The following dataset properties are specific to stacked bar charts.
| Name | Type | Description
| ---- | ---- | -----------
| `stack` | `string` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack).
## Horizontal Bar Chart
A horizontal bar chart is a variation on a vertical bar chart. It is sometimes used to show trend data, and the comparison of multiple data sets side by side.
{% chartjs %}
{
"type": "horizontalBar",
"data": {
"labels": ["January", "February", "March", "April", "May", "June", "July"],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 80, 81, 56, 55, 40],
"fill": false,
"backgroundColor": [
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)"
],
"borderColor": [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)"
],
"borderWidth": 1
}]
},
"options": {
"scales": {
"xAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
}
{% endchartjs %}
## Example
```javascript
var myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: data,
options: options
});
```
### Config Options
The configuration options for the horizontal bar chart are the same as for the [bar chart](#scale-configuration). However, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart.
The default horizontal bar configuration is specified in `Chart.defaults.horizontalBar`.

View File

@@ -0,0 +1,115 @@
# Bubble Chart
A bubble chart is used to display three dimensions of data at the same time. The location of the bubble is determined by the first two dimensions and the corresponding horizontal and vertical axes. The third dimension is represented by the size of the individual bubbles.
{% chartjs %}
{
"type": "bubble",
"data": {
"datasets": [{
"label": "First Dataset",
"data": [{
"x": 20,
"y": 30,
"r": 15
}, {
"x": 40,
"y": 10,
"r": 10
}],
"backgroundColor": "rgb(255, 99, 132)"
}]
}
}
{% endchartjs %}
## Example Usage
```javascript
// For a bubble chart
var myBubbleChart = new Chart(ctx, {
type: 'bubble',
data: data,
options: options
});
```
## Dataset Properties
The bubble chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of the bubbles is generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderWidth`](#styling) | `number` | Yes | Yes | `3`
| [`data`](#data-structure) | `object[]` | - | - | **required**
| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `1`
| [`hoverRadius`](#interactions) | `number` | Yes | Yes | `4`
| [`hitRadius`](#interactions) | `number` | Yes | Yes | `1`
| [`label`](#general) | `string` | - | - | `undefined`
| [`order`](#general) | `number` | - | - | `0`
| [`pointStyle`](#styling) | `string` | Yes | Yes | `'circle'`
| [`rotation`](#styling) | `number` | Yes | Yes | `0`
| [`radius`](#styling) | `number` | Yes | Yes | `3`
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset.
### Styling
The style of each bubble can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | bubble background color.
| `borderColor` | bubble border color.
| `borderWidth` | bubble border width (in pixels).
| `pointStyle` | bubble [shape style](../configuration/elements#point-styles).
| `rotation` | bubble rotation (in degrees).
| `radius` | bubble radius (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
### Interactions
The interaction with each bubble can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | bubble background color when hovered.
| `hoverBorderColor` | bubble border color when hovered.
| `hoverBorderWidth` | bubble border width when hovered (in pixels).
| `hoverRadius` | bubble **additional** radius when hovered (in pixels).
| `hitRadius` | bubble **additional** radius for hit detection (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
## Default Options
We can also change the default values for the Bubble chart type. Doing so will give all bubble charts created after this point the new defaults. The default configuration for the bubble chart can be accessed at `Chart.defaults.bubble`.
## Data Structure
Bubble chart datasets need to contain a `data` array of points, each points represented by an object containing the following properties:
```javascript
{
// X Value
x: number,
// Y Value
y: number,
// Bubble radius in pixels (not scaled).
r: number
}
```
**Important:** the radius property, `r` is **not** scaled by the chart, it is the raw radius in pixels of the bubble that is drawn on the canvas.

View File

@@ -0,0 +1,136 @@
# Doughnut and Pie
Pie and doughnut charts are probably the most commonly used charts. They are divided into segments, the arc of each segment shows the proportional value of each piece of data.
They are excellent at showing the relational proportions between data.
Pie and doughnut charts are effectively the same class in Chart.js, but have one different default value - their `cutoutPercentage`. This equates what percentage of the inner should be cut out. This defaults to `0` for pie charts, and `50` for doughnuts.
They are also registered under two aliases in the `Chart` core. Other than their different default value, and different alias, they are exactly the same.
{% chartjs %}
{
"type": "doughnut",
"data": {
"labels": [
"Red",
"Blue",
"Yellow"
],
"datasets": [{
"label": "My First Dataset",
"data": [300, 50, 100],
"backgroundColor": [
"rgb(255, 99, 132)",
"rgb(54, 162, 235)",
"rgb(255, 205, 86)"
]
}]
}
}
{% endchartjs %}
## Example Usage
```javascript
// For a pie chart
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data,
options: options
});
```
```javascript
// And for a doughnut chart
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: options
});
```
## Dataset Properties
The doughnut/pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colours of the dataset's arcs are generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderAlign`](#border-alignment) | `string` | Yes | Yes | `'center'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'#fff'`
| [`borderWidth`](#styling) | `number` | Yes | Yes | `2`
| [`data`](#data-structure) | `number[]` | - | - | **required**
| [`hoverBackgroundColor`](#interations) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `undefined`
| [`weight`](#styling) | `number` | - | - | `1`
### Styling
The style of each arc can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | arc background color.
| `borderColor` | arc border color.
| `borderWidth` | arc border width (in pixels).
| `weight` | The relative thickness of the dataset. Providing a value for weight will cause the pie or doughnut dataset to be drawn with a thickness relative to the sum of all the dataset weight values.
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
### Border Alignment
The following values are supported for `borderAlign`.
* `'center'` (default)
* `'inner'`
When `'center'` is set, the borders of arcs next to each other will overlap. When `'inner'` is set, it is guaranteed that all borders will not overlap.
### Interactions
The interaction with each arc can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | arc background color when hovered.
| `hoverBorderColor` | arc border color when hovered.
| `hoverBorderWidth` | arc border width when hovered (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
## Config Options
These are the customisation options specific to Pie & Doughnut charts. These options are merged with the global chart configuration options, and form the options of the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `cutoutPercentage` | `number` | `50` - for doughnut, `0` - for pie | The percentage of the chart that is cut out of the middle.
| `rotation` | `number` | `-0.5 * Math.PI` | Starting angle to draw arcs from.
| `circumference` | `number` | `2 * Math.PI` | Sweep to allow arcs to cover.
| `animation.animateRotate` | `boolean` | `true` | If true, the chart will animate in with a rotation animation. This property is in the `options.animation` object.
| `animation.animateScale` | `boolean` | `false` | If true, will animate scaling the chart from the center outwards.
## Default Options
We can also change these default values for each Doughnut type that is created, this object is available at `Chart.defaults.doughnut`. Pie charts also have a clone of these defaults available to change at `Chart.defaults.pie`, with the only difference being `cutoutPercentage` being set to 0.
## Data Structure
For a pie chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each.
You also need to specify an array of labels so that tooltips appear correctly.
```javascript
data = {
datasets: [{
data: [10, 20, 30]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Yellow',
'Blue'
]
};
```

View File

@@ -0,0 +1,220 @@
# Line
A line chart is a way of plotting data points on a line. Often, it is used to show trend data, or the comparison of two data sets.
{% chartjs %}
{
"type": "line",
"data": {
"labels": [
"January",
"February",
"March",
"April",
"May",
"June",
"July"
],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 80, 81, 56, 55, 40],
"fill": false,
"borderColor": "rgb(75, 192, 192)",
"lineTension": 0.1
}]
},
"options": {
}
}
{% endchartjs %}
## Example Usage
```javascript
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
```
## Dataset Properties
The line chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a line is generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderCapStyle`](#line-styling) | `string` | Yes | - | `'butt'`
| [`borderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderDash`](#line-styling) | `number[]` | Yes | - | `[]`
| [`borderDashOffset`](#line-styling) | `number` | Yes | - | `0.0`
| [`borderJoinStyle`](#line-styling) | `string` | Yes | - | `'miter'`
| [`borderWidth`](#line-styling) | `number` | Yes | - | `3`
| [`cubicInterpolationMode`](#cubicinterpolationmode) | `string` | Yes | - | `'default'`
| [`clip`](#line-styling) | <code>number&#124;object</code> | - | - | `borderWidth / 2`
| [`fill`](#line-styling) | <code>boolean&#124;string</code> | Yes | - | `true`
| [`hoverBackgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderCapStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderDash`](#line-styling) | `number[]` | Yes | - | `undefined`
| [`hoverBorderDashOffset`](#line-styling) | `number` | Yes | - | `undefined`
| [`hoverBorderJoinStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderWidth`](#line-styling) | `number` | Yes | - | `undefined`
| [`label`](#general) | `string` | - | - | `''`
| [`lineTension`](#line-styling) | `number` | - | - | `0.4`
| [`order`](#general) | `number` | - | - | `0`
| [`pointBackgroundColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderWidth`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHitRadius`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHoverBackgroundColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderWidth`](#interactions) | `number` | Yes | Yes | `1`
| [`pointHoverRadius`](#interactions) | `number` | Yes | Yes | `4`
| [`pointRadius`](#point-styling) | `number` | Yes | Yes | `3`
| [`pointRotation`](#point-styling) | `number` | Yes | Yes | `0`
| [`pointStyle`](#point-styling) | <code>string&#124;Image</code> | Yes | Yes | `'circle'`
| [`showLine`](#line-styling) | `boolean` | - | - | `undefined`
| [`spanGaps`](#line-styling) | `boolean` | - | - | `undefined`
| [`steppedLine`](#stepped-line) | <code>boolean&#124;string</code> | - | - | `false`
| [`xAxisID`](#general) | `string` | - | - | first x axis
| [`yAxisID`](#general) | `string` | - | - | first y axis
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
| `xAxisID` | The ID of the x axis to plot this dataset on.
| `yAxisID` | The ID of the y axis to plot this dataset on.
### Point Styling
The style of each point can be controlled with the following properties:
| Name | Description
| ---- | ----
| `pointBackgroundColor` | The fill color for points.
| `pointBorderColor` | The border color for points.
| `pointBorderWidth` | The width of the point border in pixels.
| `pointHitRadius` | The pixel size of the non-displayed point that reacts to mouse events.
| `pointRadius` | The radius of the point shape. If set to 0, the point is not rendered.
| `pointRotation` | The rotation of the point in degrees.
| `pointStyle` | Style of the point. [more...](../configuration/elements.md#point-styles)
All these values, if `undefined`, fallback first to the dataset options then to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
### Line Styling
The style of the line can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | The line fill color.
| `borderCapStyle` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap).
| `borderColor` | The line color.
| `borderDash` | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `borderWidth` | The line width (in pixels).
| `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}`
| `fill` | How to fill the area under the line. See [area charts](area.md).
| `lineTension` | Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used.
| `showLine` | If false, the line is not drawn for this dataset.
| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `NaN` data will create a break in the line.
If the value is `undefined`, `showLine` and `spanGaps` fallback to the associated [chart configuration options](#configuration-options). The rest of the values fallback to the associated [`elements.line.*`](../configuration/elements.md#line-configuration) options.
### Interactions
The interaction with each point can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `pointHoverBackgroundColor` | Point background color when hovered.
| `pointHoverBorderColor` | Point border color when hovered.
| `pointHoverBorderWidth` | Border width of point when hovered.
| `pointHoverRadius` | The radius of the point when hovered.
### cubicInterpolationMode
The following interpolation modes are supported.
* `'default'`
* `'monotone'`
The `'default'` algorithm uses a custom weighted cubic interpolation, which produces pleasant curves for all types of datasets.
The `'monotone'` algorithm is more suited to `y = f(x)` datasets : it preserves monotonicity (or piecewise monotonicity) of the dataset being interpolated, and ensures local extremums (if any) stay at input data points.
If left untouched (`undefined`), the global `options.elements.line.cubicInterpolationMode` property is used.
### Stepped Line
The following values are supported for `steppedLine`.
* `false`: No Step Interpolation (default)
* `true`: Step-before Interpolation (eq. `'before'`)
* `'before'`: Step-before Interpolation
* `'after'`: Step-after Interpolation
* `'middle'`: Step-middle Interpolation
If the `steppedLine` value is set to anything other than false, `lineTension` will be ignored.
## Configuration Options
The line chart defines the following configuration options. These options are merged with the global chart configuration options, `Chart.defaults.global`, to form the options passed to the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `showLines` | `boolean` | `true` | If false, the lines between points are not drawn.
| `spanGaps` | `boolean` | `false` | If false, NaN data causes a break in the line.
## Default Options
It is common to want to apply a configuration setting to all created line charts. The global line chart settings are stored in `Chart.defaults.line`. Changing the global options only affects charts created after the change. Existing charts are not changed.
For example, to configure all line charts with `spanGaps = true` you would do:
```javascript
Chart.defaults.line.spanGaps = true;
```
## Data Structure
The `data` property of a dataset for a line chart can be passed in two formats.
### number[]
```javascript
data: [20, 10]
```
When the `data` array is an array of numbers, the x axis is generally a [category](../axes/cartesian/category.md#category-cartesian-axis). The points are placed onto the axis using their position in the array. When a line chart is created with a category axis, the `labels` property of the data object must be specified.
### Point[]
```javascript
data: [{
x: 10,
y: 20
}, {
x: 15,
y: 10
}]
```
This alternate is used for sparse datasets, such as those in [scatter charts](./scatter.md#scatter-chart). Each data point is specified using an object containing `x` and `y` properties.
## Stacked Area Chart
Line charts can be configured into stacked area charts by changing the settings on the y axis to enable stacking. Stacked area charts can be used to show how one data trend is made up of a number of smaller pieces.
```javascript
var stackedLine = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
stacked: true
}]
}
}
});
```

View File

@@ -0,0 +1,98 @@
# Mixed Chart Types
With Chart.js, it is possible to create mixed charts that are a combination of two or more different chart types. A common example is a bar chart that also includes a line dataset.
Creating a mixed chart starts with the initialization of a basic chart.
```javascript
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
```
At this point we have a standard bar chart. Now we need to convert one of the datasets to a line dataset.
```javascript
var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Bar Dataset',
data: [10, 20, 30, 40]
}, {
label: 'Line Dataset',
data: [50, 50, 50, 50],
// Changes this dataset to become a line
type: 'line'
}],
labels: ['January', 'February', 'March', 'April']
},
options: options
});
```
At this point we have a chart rendering how we'd like. It's important to note that the default options for a line chart are not merged in this case. Only the options for the default type are merged in. In this case, that means that the default options for a bar chart are merged because that is the type specified by the `type` field.
{% chartjs %}
{
"type": "bar",
"data": {
"labels": [
"January",
"February",
"March",
"April"
],
"datasets": [{
"label": "Bar Dataset",
"data": [10, 20, 30, 40],
"borderColor": "rgb(255, 99, 132)",
"backgroundColor": "rgba(255, 99, 132, 0.2)"
}, {
"label": "Line Dataset",
"data": [50, 50, 50, 50],
"type": "line",
"fill": false,
"borderColor": "rgb(54, 162, 235)"
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
}
{% endchartjs %}
## Drawing order
By default, datasets are drawn so that first one is top-most. This can be altered by specifying `order` option to datasets. `order` defaults to `0`.
```javascript
var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Bar Dataset',
data: [10, 20, 30, 40],
// this dataset is drawn below
order: 1
}, {
label: 'Line Dataset',
data: [10, 10, 10, 10],
type: 'line',
// this dataset is drawn on top
order: 2
}],
labels: ['January', 'February', 'March', 'April']
},
options: options
});
```

View File

@@ -0,0 +1,129 @@
# Polar Area
Polar area charts are similar to pie charts, but each segment has the same angle - the radius of the segment differs depending on the value.
This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context.
{% chartjs %}
{
"type": "polarArea",
"data": {
"labels": [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
],
"datasets": [{
"label": "My First Dataset",
"data": [11, 16, 7, 3, 14],
"backgroundColor": [
"rgb(255, 99, 132)",
"rgb(75, 192, 192)",
"rgb(255, 205, 86)",
"rgb(201, 203, 207)",
"rgb(54, 162, 235)"
]
}]
}
}
{% endchartjs %}
## Example Usage
```javascript
new Chart(ctx, {
data: data,
type: 'polarArea',
options: options
});
```
## Dataset Properties
The following options can be included in a polar area chart dataset to configure options for that specific dataset.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderAlign`](#border-alignment) | `string` | Yes | Yes | `'center'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'#fff'`
| [`borderWidth`](#styling) | `number` | Yes | Yes | `2`
| [`data`](#data-structure) | `number[]` | - | - | **required**
| [`hoverBackgroundColor`](#interations) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `undefined`
### Styling
The style of each arc can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | arc background color.
| `borderColor` | arc border color.
| `borderWidth` | arc border width (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
### Border Alignment
The following values are supported for `borderAlign`.
* `'center'` (default)
* `'inner'`
When `'center'` is set, the borders of arcs next to each other will overlap. When `'inner'` is set, it is guaranteed that all the borders are not overlap.
### Interactions
The interaction with each arc can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | arc background color when hovered.
| `hoverBorderColor` | arc border color when hovered.
| `hoverBorderWidth` | arc border width when hovered (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
## Config Options
These are the customisation options specific to Polar Area charts. These options are merged with the [global chart default options](#default-options), and form the options of the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `startAngle` | `number` | `-0.5 * Math.PI` | Starting angle to draw arcs for the first item in a dataset.
| `animation.animateRotate` | `boolean` | `true` | If true, the chart will animate in with a rotation animation. This property is in the `options.animation` object.
| `animation.animateScale` | `boolean` | `true` | If true, will animate scaling the chart from the center outwards.
## Default Options
We can also change these defaults values for each PolarArea type that is created, this object is available at `Chart.defaults.polarArea`. Changing the global options only affects charts created after the change. Existing charts are not changed.
For example, to configure all new polar area charts with `animateScale = false` you would do:
```javascript
Chart.defaults.polarArea.animation.animateScale = false;
```
## Data Structure
For a polar area chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each.
You also need to specify an array of labels so that tooltips appear correctly for each slice.
```javascript
data = {
datasets: [{
data: [10, 20, 30]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Yellow',
'Blue'
]
};
```

View File

@@ -0,0 +1,202 @@
# Radar
A radar chart is a way of showing multiple data points and the variation between them.
They are often useful for comparing the points of two or more different data sets.
{% chartjs %}
{
"type": "radar",
"data": {
"labels": [
"Eating",
"Drinking",
"Sleeping",
"Designing",
"Coding",
"Cycling",
"Running"
],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 90, 81, 56, 55, 40],
"fill": true,
"backgroundColor": "rgba(255, 99, 132, 0.2)",
"borderColor": "rgb(255, 99, 132)",
"pointBackgroundColor": "rgb(255, 99, 132)",
"pointBorderColor": "#fff",
"pointHoverBackgroundColor": "#fff",
"pointHoverBorderColor": "rgb(255, 99, 132)",
"fill": true
}, {
"label": "My Second Dataset",
"data": [28, 48, 40, 19, 96, 27, 100],
"fill": true,
"backgroundColor": "rgba(54, 162, 235, 0.2)",
"borderColor": "rgb(54, 162, 235)",
"pointBackgroundColor": "rgb(54, 162, 235)",
"pointBorderColor": "#fff",
"pointHoverBackgroundColor": "#fff",
"pointHoverBorderColor": "rgb(54, 162, 235)",
"fill": true
}]
},
"options": {
"elements": {
"line": {
"tension": 0,
"borderWidth": 3
}
}
}
}
{% endchartjs %}
## Example Usage
```javascript
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data,
options: options
});
```
## Dataset Properties
The radar chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a line is generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderCapStyle`](#line-styling) | `string` | Yes | - | `'butt'`
| [`borderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderDash`](#line-styling) | `number[]` | Yes | - | `[]`
| [`borderDashOffset`](#line-styling) | `number` | Yes | - | `0.0`
| [`borderJoinStyle`](#line-styling) | `string` | Yes | - | `'miter'`
| [`borderWidth`](#line-styling) | `number` | Yes | - | `3`
| [`hoverBackgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderCapStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderDash`](#line-styling) | `number[]` | Yes | - | `undefined`
| [`hoverBorderDashOffset`](#line-styling) | `number` | Yes | - | `undefined`
| [`hoverBorderJoinStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderWidth`](#line-styling) | `number` | Yes | - | `undefined`
| [`fill`](#line-styling) | <code>boolean&#124;string</code> | Yes | - | `true`
| [`label`](#general) | `string` | - | - | `''`
| [`order`](#general) | `number` | - | - | `0`
| [`lineTension`](#line-styling) | `number` | - | - | `0`
| [`pointBackgroundColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderWidth`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHitRadius`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHoverBackgroundColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderWidth`](#interactions) | `number` | Yes | Yes | `1`
| [`pointHoverRadius`](#interactions) | `number` | Yes | Yes | `4`
| [`pointRadius`](#point-styling) | `number` | Yes | Yes | `3`
| [`pointRotation`](#point-styling) | `number` | Yes | Yes | `0`
| [`pointStyle`](#point-styling) | <code>string&#124;Image</code> | Yes | Yes | `'circle'`
| [`spanGaps`](#line-styling) | `boolean` | - | - | `undefined`
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset.
### Point Styling
The style of each point can be controlled with the following properties:
| Name | Description
| ---- | ----
| `pointBackgroundColor` | The fill color for points.
| `pointBorderColor` | The border color for points.
| `pointBorderWidth` | The width of the point border in pixels.
| `pointHitRadius` | The pixel size of the non-displayed point that reacts to mouse events.
| `pointRadius` | The radius of the point shape. If set to 0, the point is not rendered.
| `pointRotation` | The rotation of the point in degrees.
| `pointStyle` | Style of the point. [more...](../configuration/elements#point-styles)
All these values, if `undefined`, fallback first to the dataset options then to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
### Line Styling
The style of the line can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | The line fill color.
| `borderCapStyle` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap).
| `borderColor` | The line color.
| `borderDash` | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `borderWidth` | The line width (in pixels).
| `fill` | How to fill the area under the line. See [area charts](area.md).
| `lineTension` | Bezier curve tension of the line. Set to 0 to draw straightlines.
| `spanGaps` | If true, lines will be drawn between points with no or null data. If false, points with `NaN` data will create a break in the line.
If the value is `undefined`, `spanGaps` fallback to the associated [chart configuration options](#configuration-options). The rest of the values fallback to the associated [`elements.line.*`](../configuration/elements.md#line-configuration) options.
### Interactions
The interaction with each point can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `pointHoverBackgroundColor` | Point background color when hovered.
| `pointHoverBorderColor` | Point border color when hovered.
| `pointHoverBorderWidth` | Border width of point when hovered.
| `pointHoverRadius` | The radius of the point when hovered.
## Configuration Options
The radar chart defines the following configuration options. These options are merged with the global chart configuration options, `Chart.defaults.global`, to form the options passed to the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `spanGaps` | `boolean` | `false` | If false, NaN data causes a break in the line.
## Scale Options
The radar chart supports only a single scale. The options for this scale are defined in the `scale` property.
The options for this scale are defined in the `scale` property, which can be referenced from the [Linear Radial Axis page](../axes/radial/linear).
```javascript
options = {
scale: {
angleLines: {
display: false
},
ticks: {
suggestedMin: 50,
suggestedMax: 100
}
}
};
```
## Default Options
It is common to want to apply a configuration setting to all created radar charts. The global radar chart settings are stored in `Chart.defaults.radar`. Changing the global options only affects charts created after the change. Existing charts are not changed.
## Data Structure
The `data` property of a dataset for a radar chart is specified as an array of numbers. Each point in the data array corresponds to the label at the same index.
```javascript
data: [20, 10]
```
For a radar chart, to provide context of what each point means, we include an array of strings that show around each point in the chart.
```javascript
data: {
labels: ['Running', 'Swimming', 'Eating', 'Cycling'],
datasets: [{
data: [20, 10, 4, 2]
}]
}
```

View File

@@ -0,0 +1,50 @@
# Scatter Chart
Scatter charts are based on basic line charts with the x axis changed to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 3 points.
```javascript
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
```
## Dataset Properties
The scatter chart supports all of the same properties as the [line chart](./line.md#dataset-properties).
## Data Structure
Unlike the line chart where data can be supplied in two different formats, the scatter chart only accepts data in a point format.
```javascript
data: [{
x: 10,
y: 20
}, {
x: 15,
y: 10
}]
```

View File

@@ -0,0 +1,70 @@
# Configuration
The configuration is used to change how the chart behaves. There are properties to control styling, fonts, the legend, etc.
## Global Configuration
This concept was introduced in Chart.js 1.0 to keep configuration [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type.
Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in `Chart.defaults.global`. The defaults for each chart type are discussed in the documentation for that chart type.
The following example would set the hover mode to 'nearest' for all charts where this was not overridden by the chart type defaults or the options passed to the constructor on creation.
```javascript
Chart.defaults.global.hover.mode = 'nearest';
// Hover mode is set to nearest because it was not overridden here
var chartHoverModeNearest = new Chart(ctx, {
type: 'line',
data: data
});
// This chart would have the hover mode that was passed in
var chartDifferentHoverMode = new Chart(ctx, {
type: 'line',
data: data,
options: {
hover: {
// Overrides the global setting
mode: 'index'
}
}
});
```
## Dataset Configuration
Options may be configured directly on the dataset. The dataset options can be changed at 3 different levels and are evaluated with the following priority:
- per dataset: dataset.*
- per chart: options.datasets[type].*
- or globally: Chart.defaults.global.datasets[type].*
where type corresponds to the dataset type.
*Note:* dataset options take precedence over element options.
The following example would set the `showLine` option to 'false' for all line datasets except for those overridden by options passed to the dataset on creation.
```javascript
// Do not show lines for all datasets by default
Chart.defaults.global.datasets.line.showLine = false;
// This chart would show a line only for the third dataset
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [0, 0],
}, {
data: [0, 1]
}, {
data: [1, 0],
showLine: true // overrides the `line` dataset default
}, {
type: 'scatter', // 'line' dataset default does not affect this dataset since it's a 'scatter'
data: [1, 1]
}]
}
});
```

View File

@@ -0,0 +1,97 @@
# Animations
Chart.js animates charts out of the box. A number of options are provided to configure how the animation looks and how long it takes.
## Animation Configuration
The following animation options are available. The global options for are defined in `Chart.defaults.global.animation`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `duration` | `number` | `1000` | The number of milliseconds an animation takes.
| `easing` | `string` | `'easeOutQuart'` | Easing function to use. [more...](#easing)
| `onProgress` | `function` | `null` | Callback called on each step of an animation. [more...](#animation-callbacks)
| `onComplete` | `function` | `null` | Callback called at the end of an animation. [more...](#animation-callbacks)
## Easing
Available options are:
* `'linear'`
* `'easeInQuad'`
* `'easeOutQuad'`
* `'easeInOutQuad'`
* `'easeInCubic'`
* `'easeOutCubic'`
* `'easeInOutCubic'`
* `'easeInQuart'`
* `'easeOutQuart'`
* `'easeInOutQuart'`
* `'easeInQuint'`
* `'easeOutQuint'`
* `'easeInOutQuint'`
* `'easeInSine'`
* `'easeOutSine'`
* `'easeInOutSine'`
* `'easeInExpo'`
* `'easeOutExpo'`
* `'easeInOutExpo'`
* `'easeInCirc'`
* `'easeOutCirc'`
* `'easeInOutCirc'`
* `'easeInElastic'`
* `'easeOutElastic'`
* `'easeInOutElastic'`
* `'easeInBack'`
* `'easeOutBack'`
* `'easeInOutBack'`
* `'easeInBounce'`
* `'easeOutBounce'`
* `'easeInOutBounce'`
See [Robert Penner's easing equations](http://robertpenner.com/easing/).
## Animation Callbacks
The `onProgress` and `onComplete` callbacks are useful for synchronizing an external draw to the chart animation. The callback is passed a `Chart.Animation` instance:
```javascript
{
// Chart object
chart: Chart,
// Current Animation frame number
currentStep: number,
// Number of animation frames
numSteps: number,
// Animation easing to use
easing: string,
// Function that renders the chart
render: function,
// User callback
onAnimationProgress: function,
// User callback
onAnimationComplete: function
}
```
The following example fills a progress bar during the chart animation.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: {
onProgress: function(animation) {
progress.value = animation.animationObject.currentStep / animation.animationObject.numSteps;
}
}
}
});
```
Another example usage of these callbacks can be found on [Github](https://github.com/chartjs/Chart.js/blob/master/samples/advanced/progress-bar.html): this sample displays a progress bar showing how far along the animation is.

View File

@@ -0,0 +1,89 @@
# Elements
While chart types provide settings to configure the styling of each dataset, you sometimes want to style **all datasets the same way**. A common example would be to stroke all of the bars in a bar chart with the same colour but change the fill per dataset. Options can be configured for four different types of elements: **[arc](#arc-configuration)**, **[lines](#line-configuration)**, **[points](#point-configuration)**, and **[rectangles](#rectangle-configuration)**. When set, these options apply to all objects of that type unless specifically overridden by the configuration attached to a dataset.
## Global Configuration
The element options can be specified per chart or globally. The global options for elements are defined in `Chart.defaults.global.elements`. For example, to set the border width of all bar charts globally you would do:
```javascript
Chart.defaults.global.elements.rectangle.borderWidth = 2;
```
## Point Configuration
Point elements are used to represent the points in a line, radar or bubble chart.
Global point options: `Chart.defaults.global.elements.point`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `radius` | `number` | `3` | Point radius.
| [`pointStyle`](#point-styles) | <code>string&#124;Image</code> | `'circle'` | Point style.
| `rotation` | `number` | `0` | Point rotation (in degrees).
| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Point fill color.
| `borderWidth` | `number` | `1` | Point stroke width.
| `borderColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Point stroke color.
| `hitRadius` | `number` | `1` | Extra radius added to point radius for hit detection.
| `hoverRadius` | `number` | `4` | Point radius when hovered.
| `hoverBorderWidth` | `number` | `1` | Stroke width when hovered.
### Point Styles
The following values are supported:
- `'circle'`
- `'cross'`
- `'crossRot'`
- `'dash'`
- `'line'`
- `'rect'`
- `'rectRounded'`
- `'rectRot'`
- `'star'`
- `'triangle'`
If the value is an image, that image is drawn on the canvas using [drawImage](https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage).
## Line Configuration
Line elements are used to represent the line in a line chart.
Global line options: `Chart.defaults.global.elements.line`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `tension` | `number` | `0.4` | Bézier curve tension (`0` for no Bézier curves).
| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Line fill color.
| `borderWidth` | `number` | `3` | Line stroke width.
| `borderColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Line stroke color.
| `borderCapStyle` | `string` | `'butt'` | Line cap style. See [MDN](https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap).
| `borderDash` | `number[]` | `[]` | Line dash. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | `number` | `0.0` | Line dash offset. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | `string` | `'miter'` | Line join style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `capBezierPoints` | `boolean` | `true` | `true` to keep Bézier control inside the chart, `false` for no restriction.
| `cubicInterpolationMode` | `string` | `'default'` | Interpolation mode to apply. [See more...](../charts/line.md#cubicinterpolationmode)
| `fill` | <code>boolean&#124;string</code> | `true` | How to fill the area under the line. See [area charts](../charts/area.md#filling-modes).
| `stepped` | `boolean` | `false` | `true` to show the line as a stepped line (`tension` will be ignored).
## Rectangle Configuration
Rectangle elements are used to represent the bars in a bar chart.
Global rectangle options: `Chart.defaults.global.elements.rectangle`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Bar fill color.
| `borderWidth` | `number` | `0` | Bar stroke width.
| `borderColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Bar stroke color.
| `borderSkipped` | `string` | `'bottom'` | Skipped (excluded) border: `'bottom'`, `'left'`, `'top'` or `'right'`.
## Arc Configuration
Arcs are used in the polar area, doughnut and pie charts.
Global arc options: `Chart.defaults.global.elements.arc`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `angle` - for polar only | `number` | `circumference / (arc count)` | Arc angle to cover.
| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Arc fill color.
| `borderAlign` | `string` | `'center'` | Arc stroke alignment.
| `borderColor` | `Color` | `'#fff'` | Arc stroke color.
| `borderWidth`| `number` | `2` | Arc stroke width.

View File

@@ -0,0 +1,29 @@
# Layout Configuration
The layout configuration is passed into the `options.layout` namespace. The global options for the chart layout is defined in `Chart.defaults.global.layout`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `padding` | <code>number&#124;object</code> | `0` | The padding to add inside the chart. [more...](#padding)
## Padding
If this value is a number, it is applied to all sides of the chart (left, top, right, bottom). If this value is an object, the `left` property defines the left padding. Similarly the `right`, `top` and `bottom` properties can also be specified.
Lets say you wanted to add 50px of padding to the left side of the chart canvas, you would do:
```javascript
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
layout: {
padding: {
left: 50,
right: 0,
top: 0,
bottom: 0
}
}
}
});
```

View File

@@ -0,0 +1,185 @@
# Legend Configuration
The chart legend displays data about the datasets that are appearing on the chart.
## Configuration options
The legend configuration is passed into the `options.legend` namespace. The global options for the chart legend is defined in `Chart.defaults.global.legend`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `true` | Is the legend shown?
| `position` | `string` | `'top'` | Position of the legend. [more...](#position)
| `align` | `string` | `'center'` | Alignment of the legend. [more...](#align)
| `fullWidth` | `boolean` | `true` | Marks that this box should take the full width of the canvas (pushing down other boxes). This is unlikely to need to be changed in day-to-day use.
| `onClick` | `function` | | A callback that is called when a click event is registered on a label item.
| `onHover` | `function` | | A callback that is called when a 'mousemove' event is registered on top of a label item.
| `onLeave` | `function` | | A callback that is called when a 'mousemove' event is registered outside of a previously hovered label item.
| `reverse` | `boolean` | `false` | Legend will show datasets in reverse order.
| `labels` | `object` | | See the [Legend Label Configuration](#legend-label-configuration) section below.
| `rtl` | `boolean` | | `true` for rendering the legends from right to left.
| `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'|'ltr` on the canvas for rendering the legend, regardless of the css specified on the canvas
## Position
Position of the legend. Options are:
* `'top'`
* `'left'`
* `'bottom'`
* `'right'`
## Align
Alignment of the legend. Options are:
* `'start'`
* `'center'`
* `'end'`
Defaults to `'center'` for unrecognized values.
## Legend Label Configuration
The legend label configuration is nested below the legend configuration using the `labels` key.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `boxWidth` | `number` | `40` | Width of coloured box.
| `fontSize` | `number` | `12` | Font size of text.
| `fontStyle` | `string` | `'normal'` | Font style of text.
| `fontColor` | `Color` | `'#666'` | Color of text.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family of legend text.
| `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. See [Legend Item](#legend-item-interface) for details.
| `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#legend-item-interface) and the chart data.
| `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on the mimimum value between boxWidth and fontSize).
## Legend Item Interface
Items passed to the legend `onClick` function are the ones returned from `labels.generateLabels`. These items must implement the following interface.
```javascript
{
// Label that will be displayed
text: string,
// Fill style of the legend box
fillStyle: Color,
// If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect
hidden: boolean,
// For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap
lineCap: string,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
lineDash: number[],
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
lineDashOffset: number,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
lineJoin: string,
// Width of box border
lineWidth: number,
// Stroke style of the legend box
strokeStyle: Color,
// Point style of the legend box (only used if usePointStyle is true)
pointStyle: string | Image,
// Rotation of the point in degrees (only used if usePointStyle is true)
rotation: number
}
```
## Example
The following example will create a chart with the legend enabled and turn all of the text red in color.
```javascript
var chart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
legend: {
display: true,
labels: {
fontColor: 'rgb(255, 99, 132)'
}
}
}
});
```
## Custom On Click Actions
It can be common to want to trigger different behaviour when clicking an item in the legend. This can be easily achieved using a callback in the config object.
The default legend click handler is:
```javascript
function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var meta = ci.getDatasetMeta(index);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
ci.update();
}
```
Lets say we wanted instead to link the display of the first two datasets. We could change the click handler accordingly.
```javascript
var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
var newLegendClickHandler = function (e, legendItem) {
var index = legendItem.datasetIndex;
if (index > 1) {
// Do the original logic
defaultLegendClickHandler(e, legendItem);
} else {
let ci = this.chart;
[
ci.getDatasetMeta(0),
ci.getDatasetMeta(1)
].forEach(function(meta) {
meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
});
ci.update();
}
};
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
onClick: newLegendClickHandler
}
}
});
```
Now when you click the legend in this chart, the visibility of the first two datasets will be linked together.
## HTML Legends
Sometimes you need a very complex legend. In these cases, it makes sense to generate an HTML legend. Charts provide a `generateLegend()` method on their prototype that returns an HTML string for the legend.
To configure how this legend is generated, you can change the `legendCallback` config property.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legendCallback: function(chart) {
// Return the HTML string here.
}
}
});
```
Note that legendCallback is not called automatically and you must call `generateLegend()` yourself in code when creating a legend using this method.

View File

@@ -0,0 +1,42 @@
# Title
The chart title defines text to draw at the top of the chart.
## Title Configuration
The title configuration is passed into the `options.title` namespace. The global options for the chart title is defined in `Chart.defaults.global.title`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `false` | Is the title shown?
| `position` | `string` | `'top'` | Position of title. [more...](#position)
| `fontSize` | `number` | `12` | Font size.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the title text.
| `fontColor` | `Color` | `'#666'` | Font color.
| `fontStyle` | `string` | `'bold'` | Font style.
| `padding` | `number` | `10` | Number of pixels to add above and below the title text.
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text. See [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height).
| `text` | <code>string&#124;string[]</code> | `''` | Title text to display. If specified as an array, text is rendered on multiple lines.
### Position
Possible title position values are:
* `'top'`
* `'left'`
* `'bottom'`
* `'right'`
## Example Usage
The example below would enable a title of 'Custom Chart Title' on the chart that is created.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
title: {
display: true,
text: 'Custom Chart Title'
}
}
});
```

View File

@@ -0,0 +1,378 @@
# Tooltips
## Tooltip Configuration
The tooltip configuration is passed into the `options.tooltips` namespace. The global options for the chart tooltips is defined in `Chart.defaults.global.tooltips`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `enabled` | `boolean` | `true` | Are on-canvas tooltips enabled?
| `custom` | `function` | `null` | See [custom tooltip](#external-custom-tooltips) section.
| `mode` | `string` | `'nearest'` | Sets which elements appear in the tooltip. [more...](../general/interactions/modes.md#interaction-modes).
| `intersect` | `boolean` | `true` | 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. [more...](#position-modes)
| `callbacks` | `object` | | See the [callbacks section](#tooltip-callbacks).
| `itemSort` | `function` | | Sort tooltip items. [more...](#sort-callback)
| `filter` | `function` | | Filter tooltip items. [more...](#filter-callback)
| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.8)'` | Background color of the tooltip.
| `titleFontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Title font.
| `titleFontSize` | `number` | `12` | Title font size.
| `titleFontStyle` | `string` | `'bold'` | Title font style.
| `titleFontColor` | `Color` | `'#fff'` | Title font color.
| `titleAlign` | `string` | `'left'` | Horizontal alignment of the title text lines. [more...](#alignment)
| `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.
| `bodyFontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Body line font.
| `bodyFontSize` | `number` | `12` | Body font size.
| `bodyFontStyle` | `string` | `'normal'` | Body font style.
| `bodyFontColor` | `Color` | `'#fff'` | Body font color.
| `bodyAlign` | `string` | `'left'` | Horizontal alignment of the body text lines. [more...](#alignment)
| `bodySpacing` | `number` | `2` | Spacing to add to top and bottom of each tooltip item.
| `footerFontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Footer font.
| `footerFontSize` | `number` | `12` | Footer font size.
| `footerFontStyle` | `string` | `'bold'` | Footer font style.
| `footerFontColor` | `Color` | `'#fff'` | Footer font color.
| `footerAlign` | `string` | `'left'` | Horizontal alignment of the footer text lines. [more...](#alignment)
| `footerSpacing` | `number` | `2` | Spacing to add to top and bottom of each footer line.
| `footerMarginTop` | `number` | `6` | Margin to add before drawing the footer.
| `xPadding` | `number` | `6` | Padding to add on left and right of tooltip.
| `yPadding` | `number` | `6` | Padding to add on top and bottom of 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` | `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.
| `borderColor` | `Color` | `'rgba(0, 0, 0, 0)'` | Color of the border.
| `borderWidth` | `number` | `0` | Size of the border.
| `rtl` | `boolean` | | `true` for rendering the legends from right to left.
| `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'|'ltr` on the canvas for rendering the tooltips, regardless of the css specified on the canvas
### Position Modes
Possible modes are:
* `'average'`
* `'nearest'`
`'average'` mode will place the tooltip at the average position of the items displayed in the tooltip. `'nearest'` will place the tooltip at the position of the element closest to the event position.
New modes can be defined by adding functions to the `Chart.Tooltip.positioners` map.
Example:
```javascript
/**
* Custom positioner
* @function Chart.Tooltip.positioners.custom
* @param elements {Chart.Element[]} the tooltip elements
* @param eventPosition {Point} the position of the event in canvas coordinates
* @returns {Point} the tooltip position
*/
Chart.Tooltip.positioners.custom = function(elements, eventPosition) {
/** @type {Chart.Tooltip} */
var tooltip = this;
/* ... */
return {
x: 0,
y: 0
};
};
```
### Alignment
The `titleAlign`, `bodyAlign` and `footerAlign` options define the horizontal position of the text lines with respect to the tooltip box. The following values are supported.
* `'left'` (default)
* `'right'`
* `'center'`
These options are only applied to text lines. Color boxes are always aligned to the left edge.
### Sort Callback
Allows sorting of [tooltip items](#tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). This function can also accept a third parameter that is the data object passed to the chart.
### Filter Callback
Allows filtering of [tooltip items](#tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.filter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). This function can also accept a second parameter that is the data object passed to the chart.
## Tooltip Callbacks
The tooltip label configuration is nested below the tooltip configuration using the `callbacks` key. The tooltip has the following callbacks for providing text. For all functions, `this` will be the tooltip object created from the `Chart.Tooltip` constructor.
All functions are called with the same arguments: a [tooltip item](#tooltip-item-interface) and the `data` object passed to the chart. All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text.
| Name | Arguments | Description
| ---- | --------- | -----------
| `beforeTitle` | `TooltipItem[], object` | Returns the text to render before the title.
| `title` | `TooltipItem[], object` | Returns text to render as the title of the tooltip.
| `afterTitle` | `TooltipItem[], object` | Returns text to render after the title.
| `beforeBody` | `TooltipItem[], object` | Returns text to render before the body section.
| `beforeLabel` | `TooltipItem, object` | Returns text to render before an individual label. This will be called for each item in the tooltip.
| `label` | `TooltipItem, object` | Returns text to render for an individual item in the tooltip. [more...](#label-callback)
| `labelColor` | `TooltipItem, Chart` | Returns the colors to render for the tooltip item. [more...](#label-color-callback)
| `labelTextColor` | `TooltipItem, Chart` | Returns the colors for the text of the label for the tooltip item.
| `afterLabel` | `TooltipItem, object` | Returns text to render after an individual label.
| `afterBody` | `TooltipItem[], object` | Returns text to render after the body section.
| `beforeFooter` | `TooltipItem[], object` | Returns text to render before the footer section.
| `footer` | `TooltipItem[], object` | Returns text to render as the footer of the tooltip.
| `afterFooter` | `TooltipItem[], object` | Text to render after the footer section.
### Label Callback
The `label` callback can change the text that displays for a given data point. A common example to round data values; the following example rounds the data to two decimal places.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += Math.round(tooltipItem.yLabel * 100) / 100;
return label;
}
}
}
}
});
```
### Label Color Callback
For example, to return a red box for each item in the tooltip you could do:
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
callbacks: {
labelColor: function(tooltipItem, chart) {
return {
borderColor: 'rgb(255, 0, 0)',
backgroundColor: 'rgb(255, 0, 0)'
};
},
labelTextColor: function(tooltipItem, chart) {
return '#543453';
}
}
}
}
});
```
### Tooltip Item Interface
The tooltip items passed to the tooltip callbacks implement the following interface.
```javascript
{
// Label for the tooltip
label: string,
// Value for the tooltip
value: string,
// X Value of the tooltip
// (deprecated) use `value` or `label` instead
xLabel: number | string,
// Y value of the tooltip
// (deprecated) use `value` or `label` instead
yLabel: number | string,
// Index of the dataset the item comes from
datasetIndex: number,
// Index of this data item in the dataset
index: number,
// X position of matching point
x: number,
// Y position of matching point
y: number
}
```
## External (Custom) Tooltips
Custom tooltips allow you to hook into the tooltip rendering process so that you can render the tooltip in your own custom way. Generally this is used to create an HTML tooltip instead of an oncanvas one. You can enable custom tooltips in the global or chart configuration like so:
```javascript
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
tooltips: {
// Disable the on-canvas tooltip
enabled: false,
custom: function(tooltipModel) {
// Tooltip Element
var 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
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) {
var titleLines = tooltipModel.title || [];
var bodyLines = tooltipModel.body.map(getBody);
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltipModel.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
// `this` will be the overall tooltip
var position = this._chart.canvas.getBoundingClientRect();
// 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.fontFamily = tooltipModel._bodyFontFamily;
tooltipEl.style.fontSize = tooltipModel.bodyFontSize + 'px';
tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
tooltipEl.style.pointerEvents = 'none';
}
}
}
});
```
See [samples](https://www.chartjs.org/samples/) for examples on how to get started with custom tooltips.
## Tooltip Model
The tooltip model contains parameters that can be used to render the tooltip.
```javascript
{
// The items that we are rendering in the tooltip. See Tooltip Item Interface section
dataPoints: TooltipItem[],
// Positioning
xPadding: number,
yPadding: number,
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[],
bodyFontColor: Color,
_bodyFontFamily: string,
_bodyFontStyle: string,
_bodyAlign: string,
bodyFontSize: number,
bodySpacing: number,
// Title
// lines of text that form the title
title: string[],
titleFontColor: Color,
_titleFontFamily: string,
_titleFontStyle: string,
titleFontSize: number,
_titleAlign: string,
titleSpacing: number,
titleMarginBottom: number,
// Footer
// lines of text that form the footer
footer: string[],
footerFontColor: Color,
_footerFontFamily: string,
_footerFontStyle: string,
footerFontSize: number,
_footerAlign: string,
footerSpacing: number,
footerMarginTop: number,
// Appearance
caretSize: number,
caretPadding: number,
cornerRadius: number,
backgroundColor: Color,
// colors to render for each item in body[]. This is the color of the squares in the tooltip
labelColors: Color[],
labelTextColors: Color[],
// 0 opacity is a hidden tooltip
opacity: number,
legendColorBackground: Color,
displayColors: boolean,
borderColor: Color,
borderWidth: number
}
```

View File

@@ -0,0 +1,46 @@
# Developers
Developer features allow extending and enhancing Chart.js in many different ways.
## Latest resources
Latest documentation and samples, including unreleased features, are available at:
- https://www.chartjs.org/docs/master/
- https://www.chartjs.org/samples/master/
## Development releases
Latest builds are available for testing at:
- https://www.chartjs.org/dist/master/Chart.min.js
- https://www.chartjs.org/dist/master/Chart.bundle.min.js
> Note: Development builds are currently only available via HTTP, so in order to include them in [JSFiddle](https://jsfiddle.net) or [CodePen](https://codepen.io), you need to access these tools via HTTP as well.
**WARNING: Development builds MUST not be used for production purposes or as replacement for CDN.**
## Browser support
Chart.js offers support for the following browsers:
* Chrome 50+
* Firefox 45+
* Internet Explorer 11
* Edge 14+
* Safari 9+
Browser support for the canvas element is available in all modern & major mobile browsers. [CanIUse](https://caniuse.com/#feat=canvas)
Thanks to [BrowserStack](https://browserstack.com) for allowing our team to test on thousands of browsers.
## Previous versions
Version 2 has a completely different API than earlier versions.
Most earlier version options have current equivalents or are the same.
Please use the documentation that is available on [chartjs.org](https://www.chartjs.org/docs/) for the current version of Chart.js.
Please note - documentation for previous versions are available on the GitHub repo.
- [1.x Documentation](https://github.com/chartjs/Chart.js/tree/v1.1.1/docs)

View File

@@ -0,0 +1,179 @@
# Chart Prototype Methods
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.
```javascript
// For example:
var myLineChart = new Chart(ctx, config);
```
## .destroy()
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.
```javascript
// Destroys a specific chart instance
myLineChart.destroy();
```
## .update(config)
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.
```javascript
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
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.
```
> **Note:** replacing the data reference (e.g. `myLineChart.data = {datasets: [...]}` only works starting **version 2.6**. Prior that, replacing the entire data object could be achieved with the following workaround: `myLineChart.config.data = {datasets: [...]}`.
A `config` object can be provided with additional configuration for the update process. This is useful when `update` is manually called inside an event handler and some different animation is desired.
The following properties are supported:
* **duration** (number): Time for the animation of the redraw in milliseconds
* **lazy** (boolean): If true, the animation can be interrupted by other animations
* **easing** (string): The animation easing function. See [Animation Easing](../configuration/animations.md) for possible values.
Example:
```javascript
myChart.update({
duration: 800,
easing: 'easeOutBounce'
});
```
See [Updating Charts](updates.md) for more details.
## .reset()
Reset the chart to it's state before the initial animation. A new animation can then be triggered using `update`.
```javascript
myLineChart.reset();
```
## .render(config)
Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use `.update()` in that case.
See `.update(config)` for more details on the config object.
```javascript
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
myLineChart.render({
duration: 800,
lazy: false,
easing: 'easeOutBounce'
});
```
## .stop()
Use this to stop any current animation loop. This will pause the chart during any current animation frame. Call `.render()` to re-animate.
```javascript
// Stops the charts animation loop at its current frame
myLineChart.stop();
// => returns 'this' for chainability
```
## .resize()
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.
```javascript
// Resizes & redraws to fill its container element
myLineChart.resize();
// => returns 'this' for chainability
```
## .clear()
Will clear the chart canvas. Used extensively internally between animation frames, but you might find it useful.
```javascript
// Will clear the canvas that myLineChart is drawn on
myLineChart.clear();
// => returns 'this' for chainability
```
## .toBase64Image()
This returns a base 64 encoded string of the chart in it's current state.
```javascript
myLineChart.toBase64Image();
// => returns png data url of the image on the canvas
```
## .generateLegend()
Returns an HTML string of a legend for that chart. The legend is generated from the `legendCallback` in the options.
```javascript
myLineChart.generateLegend();
// => returns HTML string of a legend for this chart
```
## .getElementAtEvent(e)
Calling `getElementAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the single element at the event position. If there are multiple items within range, only the first is returned. The value returned from this method is an array with a single parameter. An array is used to keep a consistent API between the `get*AtEvent` methods.
```javascript
myLineChart.getElementAtEvent(e);
// => returns the first element at the event point.
```
To get an item that was clicked on, `getElementAtEvent` can be used.
```javascript
function clickHandler(evt) {
var firstPoint = myChart.getElementAtEvent(evt)[0];
if (firstPoint) {
var label = myChart.data.labels[firstPoint._index];
var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
}
}
```
## .getElementsAtEvent(e)
Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.
Calling `getElementsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
```javascript
canvas.onclick = function(evt) {
var activePoints = myLineChart.getElementsAtEvent(evt);
// => activePoints is an array of points on the canvas that are at the same position as the click event.
};
```
This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
## .getDatasetAtEvent(e)
Looks for the element under the event point, then returns all elements from that dataset. This is used internally for 'dataset' mode highlighting.
```javascript
myLineChart.getDatasetAtEvent(e);
// => returns an array of elements
```
## .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.
The `data` property of the metadata will contain information about each point, rectangle, etc. depending on the chart type.
Extensive examples of usage are available in the [Chart.js tests](https://github.com/chartjs/Chart.js/tree/master/test).
```javascript
var meta = myChart.getDatasetMeta(0);
var x = meta.data[0]._model.x;
```

View File

@@ -0,0 +1,134 @@
# New Axes
Axes in Chart.js can be individually extended. Axes should always derive from `Chart.Scale` but this is not a mandatory requirement.
```javascript
let MyScale = Chart.Scale.extend({
/* extensions ... */
});
// MyScale is now derived from Chart.Scale
```
Once you have created your scale class, you need to register it with the global chart object so that it can be used. A default config for the scale may be provided when registering the constructor. The first parameter to the register function is a string key that is used later to identify which scale type to use for a chart.
```javascript
Chart.scaleService.registerScaleType('myScale', MyScale, defaultConfigObject);
```
To use the new scale, simply pass in the string key to the config when creating a chart.
```javascript
var lineChart = new Chart(ctx, {
data: data,
type: 'line',
options: {
scales: {
yAxes: [{
type: 'myScale' // this is the same key that was passed to the registerScaleType function
}]
}
}
});
```
## Scale Properties
Scale instances are given the following properties during the fitting process.
```javascript
{
left: number, // left edge of the scale bounding box
right: number, // right edge of the bounding box
top: number,
bottom: number,
width: number, // the same as right - left
height: number, // the same as bottom - top
// Margin on each side. Like css, this is outside the bounding box.
margins: {
left: number,
right: number,
top: number,
bottom: number
},
// Amount of padding on the inside of the bounding box (like CSS)
paddingLeft: number,
paddingRight: number,
paddingTop: number,
paddingBottom: number
}
```
## Scale Interface
To work with Chart.js, custom scale types must implement the following interface.
```javascript
{
// Determines the data limits. Should set this.min and this.max to be the data max/min
determineDataLimits: function() {},
// Generate tick marks. this.chart is the chart instance. The data object can be accessed as this.chart.data
// buildTicks() should create a ticks array on the axis instance, if you intend to use any of the implementations from the base class
buildTicks: function() {},
// Get the value to show for the data at the given index of the the given dataset, ie this.chart.data.datasets[datasetIndex].data[index]
getLabelForIndex: function(index, datasetIndex) {},
// Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value
// @param index: index into the ticks array
getPixelForTick: function(index) {},
// Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value
// @param value : the value to get the pixel for
// @param index : index into the data array of the value
// @param datasetIndex : index of the dataset the value comes from
getPixelForValue: function(value, index, datasetIndex) {},
// Get the value for a given pixel (x coordinate for horizontal axis, y coordinate for vertical axis)
// @param pixel : pixel value
getValueForPixel: function(pixel) {}
}
```
Optionally, the following methods may also be overwritten, but an implementation is already provided by the `Chart.Scale` base class.
```javascript
{
// Transform the ticks array of the scale instance into strings. The default implementation simply calls this.options.ticks.callback(numericalTick, index, ticks);
convertTicksToLabels: function() {},
// Determine how much the labels will rotate by. The default implementation will only rotate labels if the scale is horizontal.
calculateTickRotation: function() {},
// Fits the scale into the canvas.
// this.maxWidth and this.maxHeight will tell you the maximum dimensions the scale instance can be. Scales should endeavour to be as efficient as possible with canvas space.
// this.margins is the amount of space you have on either side of your scale that you may expand in to. This is used already for calculating the best label rotation
// You must set this.minSize to be the size of your scale. It must be an object containing 2 properties: width and height.
// You must set this.width to be the width and this.height to be the height of the scale
fit: function() {},
// Draws the scale onto the canvas. this.(left|right|top|bottom) will have been populated to tell you the area on the canvas to draw in
// @param chartArea : an object containing four properties: left, right, top, bottom. This is the rectangle that lines, bars, etc will be drawn in. It may be used, for example, to draw grid lines.
draw: function(chartArea) {}
}
```
The Core.Scale base class also has some utility functions that you may find useful.
```javascript
{
// Returns true if the scale instance is horizontal
isHorizontal: function() {},
// Get the correct value from the value from this.chart.data.datasets[x].data[]
// If dataValue is an object, returns .x or .y depending on the return of isHorizontal()
// If the value is undefined, returns NaN
// Otherwise returns the value.
// Note that in all cases, the returned value is not guaranteed to be a number
getRightValue: function(dataValue) {},
// Returns the scale tick objects ({label, major})
getTicks: function() {}
}
```

View File

@@ -0,0 +1,116 @@
# New Charts
Chart.js 2.0 introduces the concept of controllers for each dataset. Like scales, new controllers can be written as needed.
```javascript
Chart.controllers.MyType = Chart.DatasetController.extend({
});
// Now we can create a new instance of our chart, using the Chart.js API
new Chart(ctx, {
// this is the string the constructor was registered at, ie Chart.controllers.MyType
type: 'MyType',
data: data,
options: options
});
```
## Dataset Controller Interface
Dataset controllers must implement the following interface.
```javascript
{
// Create elements for each piece of data in the dataset. Store elements in an array on the dataset as dataset.metaData
addElements: function() {},
// Create a single element for the data at the given index and reset its state
addElementAndReset: function(index) {},
// Draw the representation of the dataset
// @param ease : if specified, this number represents how far to transition elements. See the implementation of draw() in any of the provided controllers to see how this should be used
draw: function(ease) {},
// Remove hover styling from the given element
removeHoverStyle: function(element) {},
// Add hover styling to the given element
setHoverStyle: function(element) {},
// Update the elements in response to new data
// @param reset : if true, put the elements into a reset state so they can animate to their final values
update: function(reset) {}
}
```
The following methods may optionally be overridden by derived dataset controllers.
```javascript
{
// Initializes the controller
initialize: function(chart, datasetIndex) {},
// Ensures that the dataset represented by this controller is linked to a scale. Overridden to helpers.noop in the polar area and doughnut controllers as these
// chart types using a single scale
linkScales: function() {},
// Called by the main chart controller when an update is triggered. The default implementation handles the number of data points changing and creating elements appropriately.
buildOrUpdateElements: function() {}
}
```
## Extending Existing Chart Types
Extending or replacing an existing controller type is easy. Simply replace the constructor for one of the built in types with your own.
The built in controller types are:
* `Chart.controllers.line`
* `Chart.controllers.bar`
* `Chart.controllers.radar`
* `Chart.controllers.doughnut`
* `Chart.controllers.polarArea`
* `Chart.controllers.bubble`
For example, to derive a new chart type that extends from a bubble chart, you would do the following.
```javascript
// Sets the default config for 'derivedBubble' to be the same as the bubble defaults.
// We look for the defaults by doing Chart.defaults[chartType]
// It looks like a bug exists when the defaults don't exist
Chart.defaults.derivedBubble = Chart.defaults.bubble;
// I think the recommend using Chart.controllers.bubble.extend({ extensions here });
var custom = Chart.controllers.bubble.extend({
draw: function(ease) {
// Call super method first
Chart.controllers.bubble.prototype.draw.call(this, ease);
// Now we can do some custom drawing for this dataset. Here we'll draw a red box around the first point in each dataset
var meta = this.getMeta();
var pt0 = meta.data[0];
var radius = pt0._view.radius;
var ctx = this.chart.chart.ctx;
ctx.save();
ctx.strokeStyle = 'red';
ctx.lineWidth = 1;
ctx.strokeRect(pt0._view.x - radius, pt0._view.y - radius, 2 * radius, 2 * radius);
ctx.restore();
}
});
// Stores the controller so that the chart initialization routine can look it up with
// Chart.controllers[type]
Chart.controllers.derivedBubble = custom;
// Now we can create and use our new chart type
new Chart(ctx, {
type: 'derivedBubble',
data: data,
options: options
});
```
### Bar Controller
The bar controller has a special property that you should be aware of. To correctly calculate the width of a bar, the controller must determine the number of datasets that map to bars. To do this, the bar controller attaches a property `bar` to the dataset during initialization. If you are creating a replacement or updated bar controller, you should do the same. This will ensure that charts with regular bars and your new derived bars will work seamlessly.

View File

@@ -0,0 +1,77 @@
# Contributing
New contributions to the library are welcome, but we ask that you please follow these guidelines:
- Before opening a PR for major additions or changes, please discuss the expected API and/or implementation by [filing an issue](https://github.com/chartjs/Chart.js/issues) or asking about it in the [Chart.js Slack](https://chartjs-slack.herokuapp.com/) #dev channel. This will save you development time by getting feedback upfront and make review faster by giving the maintainers more context and details.
- Consider whether your changes are useful for all users, or if creating a Chart.js [plugin](plugins.md) would be more appropriate.
- Check that your code will pass tests and `eslint` code standards. `gulp test` will run both the linter and tests for you.
- Add unit tests and document new functionality (in the `test/` and `docs/` directories respectively).
- Avoid breaking changes unless there is an upcoming major release, which are infrequent. We encourage people to write plugins for most new advanced features, and care a lot about backwards compatibility.
- We strongly prefer new methods to be added as private whenever possible. A method can be made private either by making a top-level `function` outside of a class or by prefixing it with `_` and adding `@private` JSDoc if inside a class. Public APIs take considerable time to review and become locked once implemented as we have limited ability to change them without breaking backwards compatibility. Private APIs allow the flexibility to address unforeseen cases.
## Joining the project
Active committers and contributors are invited to introduce yourself and request commit access to this project. We have a very active Slack community that you can join [here](https://chartjs-slack.herokuapp.com/). If you think you can help, we'd love to have you!
## Building and Testing
Chart.js uses <a href="https://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file.
Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following:
```bash
> npm install
> npm install -g gulp-cli
```
This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="https://gulpjs.com/" target="_blank">gulp</a>.
The following commands are now available from the repository root:
```bash
> gulp build // build dist files in ./dist
> gulp build --watch // build and watch for changes
> gulp unittest // run tests from ./test/specs
> gulp unittest --watch // run tests and watch for source changes
> gulp unittest --coverage // run tests and generate coverage reports in ./coverage
> gulp lint // perform code linting (ESLint)
> gulp test // perform code linting and run unit tests
> gulp docs // build the documentation in ./dist/docs
> gulp docs --watch // starts the gitbook live reloaded server
```
More information can be found in [gulpfile.js](https://github.com/chartjs/Chart.js/blob/master/gulpfile.js).
### Image-Based Tests
Some display-related functionality is difficult to test via typical Jasmine units. For this reason, we introduced image-based tests ([#3988](https://github.com/chartjs/Chart.js/pull/3988) and [#5777](https://github.com/chartjs/Chart.js/pull/5777)) to assert that a chart is drawn pixel-for-pixel matching an expected image.
Generated charts in image-based tests should be **as minimal as possible** and focus only on the tested feature to prevent failure if another feature breaks (e.g. disable the title and legend when testing scales).
You can create a new image-based test by following the steps below:
- Create a JS file ([example](https://github.com/chartjs/Chart.js/blob/f7b671006a86201808402c3b6fe2054fe834fd4a/test/fixtures/controller.bubble/radius-scriptable.js)) or JSON file ([example](https://github.com/chartjs/Chart.js/blob/4b421a50bfa17f73ac7aa8db7d077e674dbc148d/test/fixtures/plugin.filler/fill-line-dataset.json)) that defines chart config and generation options.
- Add this file in `test/fixtures/{spec.name}/{feature-name}.json`.
- Add a [describe line](https://github.com/chartjs/Chart.js/blob/4b421a50bfa17f73ac7aa8db7d077e674dbc148d/test/specs/plugin.filler.tests.js#L10) to the beginning of `test/specs/{spec.name}.tests.js` if it doesn't exist yet.
- Run `gulp unittest --watch --inputs=test/specs/{spec.name}.tests.js`.
- Click the *"Debug"* button (top/right): a test should fail with the associated canvas visible.
- Right click on the chart and *"Save image as..."* `test/fixtures/{spec.name}/{feature-name}.png` making sure not to activate the tooltip or any hover functionality
- Refresh the browser page (`CTRL+R`): test should now pass
- Verify test relevancy by changing the feature values *slightly* in the JSON file.
Tests should pass in both browsers. In general, we've hidden all text in image tests since it's quite difficult to get them passing between different browsers. As a result, it is recommended to hide all scales in image-based tests. It is also recommended to disable animations. If tests still do not pass, adjust [`tolerance` and/or `threshold`](https://github.com/chartjs/Chart.js/blob/1ca0ffb5d5b6c2072176fd36fa85a58c483aa434/test/jasmine.matchers.js) at the beginning of the JSON file keeping them **as low as possible**.
When a test fails, the expected and actual images are shown. If you'd like to see the images even when the tests pass, set `"debug": true` in the JSON file.
## Bugs and Issues
Please report these on the GitHub page - at <a href="https://github.com/chartjs/Chart.js" target="_blank">github.com/chartjs/Chart.js</a>. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](https://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow.
Well structured, detailed bug reports are hugely valuable for the project.
Guidelines for reporting bugs:
- Check the issue search to see if it has already been reported
- Isolate the problem to a simple test case
- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq)). If filing a bug against `master`, you may reference the latest code via https://www.chartjs.org/dist/master/Chart.min.js (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time.
Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data.

View File

@@ -0,0 +1,132 @@
# Plugins
Plugins are the most efficient way to customize or change the default behavior of a chart. They have been introduced at [version 2.1.0](https://github.com/chartjs/Chart.js/releases/tag/2.1.0) (global plugins only) and extended at [version 2.5.0](https://github.com/chartjs/Chart.js/releases/tag/v2.5.0) (per chart plugins and options).
## Using plugins
Plugins can be shared between chart instances:
```javascript
var plugin = { /* plugin implementation */ };
// chart1 and chart2 use "plugin"
var chart1 = new Chart(ctx, {
plugins: [plugin]
});
var chart2 = new Chart(ctx, {
plugins: [plugin]
});
// chart3 doesn't use "plugin"
var chart3 = new Chart(ctx, {});
```
Plugins can also be defined directly in the chart `plugins` config (a.k.a. *inline plugins*):
```javascript
var chart = new Chart(ctx, {
plugins: [{
beforeInit: function(chart, options) {
//..
}
}]
});
```
However, this approach is not ideal when the customization needs to apply to many charts.
## Global plugins
Plugins can be registered globally to be applied on all charts (a.k.a. *global plugins*):
```javascript
Chart.plugins.register({
// plugin implementation
});
```
> Note: *inline* plugins can't be registered globally.
## Configuration
### Plugin ID
Plugins must define a unique id in order to be configurable.
This id should follow the [npm package name convention](https://docs.npmjs.com/files/package.json#name):
- can't start with a dot or an underscore
- can't contain any non-URL-safe characters
- can't contain uppercase letters
- should be something short, but also reasonably descriptive
If a plugin is intended to be released publicly, you may want to check the [registry](https://www.npmjs.com/search?q=chartjs-plugin-) to see if there's something by that name already. Note that in this case, the package name should be prefixed by `chartjs-plugin-` to appear in Chart.js plugin registry.
### Plugin options
Plugin options are located under the `options.plugins` config and are scoped by the plugin ID: `options.plugins.{plugin-id}`.
```javascript
var chart = new Chart(ctx, {
options: {
foo: { ... }, // chart 'foo' option
plugins: {
p1: {
foo: { ... }, // p1 plugin 'foo' option
bar: { ... }
},
p2: {
foo: { ... }, // p2 plugin 'foo' option
bla: { ... }
}
}
}
});
```
#### Disable plugins
To disable a global plugin for a specific chart instance, the plugin options must be set to `false`:
```javascript
Chart.plugins.register({
id: 'p1',
// ...
});
var chart = new Chart(ctx, {
options: {
plugins: {
p1: false // disable plugin 'p1' for this instance
}
}
});
```
## Plugin Core API
Available hooks (as of version 2.7):
* `beforeInit`
* `afterInit`
* `beforeUpdate` *(cancellable)*
* `afterUpdate`
* `beforeLayout` *(cancellable)*
* `afterLayout`
* `beforeDatasetsUpdate` *(cancellable)*
* `afterDatasetsUpdate`
* `beforeDatasetUpdate` *(cancellable)*
* `afterDatasetUpdate`
* `beforeRender` *(cancellable)*
* `afterRender`
* `beforeDraw` *(cancellable)*
* `afterDraw`
* `beforeDatasetsDraw` *(cancellable)*
* `afterDatasetsDraw`
* `beforeDatasetDraw` *(cancellable)*
* `afterDatasetDraw`
* `beforeEvent` *(cancellable)*
* `afterEvent`
* `resize`
* `destroy`

View File

@@ -0,0 +1,101 @@
# Updating Charts
It's pretty common to want to update charts after they've been created. When the chart data or options are changed, Chart.js will animate to the new data values and options.
## Adding or Removing Data
Adding and removing data is supported by changing the data array. To add data, just add data into the data array as seen in this example.
```javascript
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
```
## Updating Options
To update the options, mutating the options property in place or passing in a new options object are supported.
- If the options are mutated in place, other option properties would be preserved, including those calculated by Chart.js.
- If created as a new object, it would be like creating a new chart with the options - old options would be discarded.
```javascript
function updateConfigByMutating(chart) {
chart.options.title.text = 'new title';
chart.update();
}
function updateConfigAsNewObject(chart) {
chart.options = {
responsive: true,
title: {
display: true,
text: 'Chart.js'
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}]
}
};
chart.update();
}
```
Scales can be updated separately without changing other options.
To update the scales, pass in an object containing all the customization including those unchanged ones.
Variables referencing any one from `chart.scales` would be lost after updating scales with a new `id` or the changed `type`.
```javascript
function updateScales(chart) {
var xScale = chart.scales['x-axis-0'];
var yScale = chart.scales['y-axis-0'];
chart.options.scales = {
xAxes: [{
id: 'newId',
display: true
}],
yAxes: [{
display: true,
type: 'logarithmic'
}]
};
chart.update();
// need to update the reference
xScale = chart.scales['newId'];
yScale = chart.scales['y-axis-0'];
}
```
You can also update a specific scale either by specifying its index or id.
```javascript
function updateScale(chart) {
chart.options.scales.yAxes[0] = {
type: 'logarithmic'
};
chart.update();
}
```
Code sample for updating options can be found in [toggle-scale-type.html](../../samples/scales/toggle-scale-type.html).
## Preventing Animations
Sometimes when a chart updates, you may not want an animation. To achieve this you can call `update` with a duration of `0`. This will render the chart synchronously and without an animation.

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();
}
}
```

View File

@@ -0,0 +1,43 @@
# Getting Started
Let's get started using Chart.js!
First, we need to have a canvas in our page.
```html
<canvas id="myChart"></canvas>
```
Now that we have a canvas we can use, we need to include Chart.js in our page.
```html
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
```
Now, we can create a chart. We add a script to our page:
```javascript
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
```
It's that easy to get started using Chart.js! From here you can explore the many options that can help you customise your charts with scales, tooltips, labels, colors, custom actions, and much more.
All our examples are [available online](https://www.chartjs.org/samples/latest/) but you can also download the `Chart.js.zip` archive attached to every [release](https://github.com/chartjs/Chart.js/releases) to experiment with our samples locally from the `/samples` folder.

View File

@@ -0,0 +1,58 @@
# Installation
Chart.js can be installed via npm or bower. It is recommended to get Chart.js this way.
## npm
[![npm](https://img.shields.io/npm/v/chart.js.svg?style=flat-square&maxAge=600)](https://npmjs.com/package/chart.js)
[![npm](https://img.shields.io/npm/dm/chart.js.svg?style=flat-square&maxAge=600)](https://npmjs.com/package/chart.js)
```bash
npm install chart.js --save
```
## Bower
[![bower](https://img.shields.io/bower/v/chartjs.svg?style=flat-square&maxAge=600)](https://libraries.io/bower/chartjs)
```bash
bower install chart.js --save
```
## CDN
### CDNJS
[![cdnjs](https://img.shields.io/cdnjs/v/Chart.js.svg?style=flat-square&maxAge=600)](https://cdnjs.com/libraries/Chart.js)
Chart.js built files are available on [CDNJS](https://cdnjs.com/):
https://cdnjs.com/libraries/Chart.js
### jsDelivr
[![jsdelivr](https://img.shields.io/npm/v/chart.js.svg?label=jsdelivr&style=flat-square&maxAge=600)](https://cdn.jsdelivr.net/npm/chart.js@latest/dist/) [![jsdelivr hits](https://data.jsdelivr.com/v1/package/npm/chart.js/badge)](https://www.jsdelivr.com/package/npm/chart.js)
Chart.js built files are also available through [jsDelivr](https://www.jsdelivr.com/):
https://www.jsdelivr.com/package/npm/chart.js?path=dist
## Github
[![github](https://img.shields.io/github/release/chartjs/Chart.js.svg?style=flat-square&maxAge=600)](https://github.com/chartjs/Chart.js/releases/latest)
You can download the latest version of [Chart.js on GitHub](https://github.com/chartjs/Chart.js/releases/latest).
If you download or clone the repository, you must [build](../developers/contributing.md#building-and-testing) Chart.js to generate the dist files. Chart.js no longer comes with prebuilt release versions, so an alternative option to downloading the repo is **strongly** advised.
## Selecting the Correct Build
Chart.js provides two different builds for you to choose: **Stand-Alone Build**, **Bundled Build**.
### Stand-Alone Build
Files:
* `dist/Chart.js`
* `dist/Chart.min.js`
The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include [Moment.js](https://momentjs.com/) before Chart.js for the functionality of the time axis.
### Bundled Build
Files:
* `dist/Chart.bundle.js`
* `dist/Chart.bundle.min.js`
The bundled build includes Moment.js in a single file. You should use this version if you require time axes and want to include a single file. You should not use this build if your application already included Moment.js. Otherwise, Moment.js will be included twice which results in increasing page load time and possible version compatibility issues. The Moment.js version in the bundled build is private to Chart.js so if you want to use Moment.js yourself, it's better to use Chart.js (non bundled) and import Moment.js manually.

View File

@@ -0,0 +1,101 @@
# Integration
Chart.js can be integrated with plain JavaScript or with different module loaders. The examples below show how to load Chart.js in different systems.
## Script Tag
```html
<script src="path/to/chartjs/dist/Chart.js"></script>
<script>
var myChart = new Chart(ctx, {...});
</script>
```
## Common JS
```javascript
var Chart = require('chart.js');
var myChart = new Chart(ctx, {...});
```
## Bundlers (Webpack, Rollup, etc.)
```javascript
import Chart from 'chart.js';
var myChart = new Chart(ctx, {...});
```
**Note:** Moment.js is installed along Chart.js as dependency. If you don't want to use Moment.js (either because you use a different date adapter or simply because don't need time functionalities), you will have to configure your bundler to exclude this dependency (e.g. using [`externals` for Webpack](https://webpack.js.org/configuration/externals/) or [`external` for Rollup](https://rollupjs.org/guide/en#peer-dependencies)).
```javascript
// Webpack
{
externals: {
moment: 'moment'
}
}
```
```javascript
// Rollup
{
external: {
['moment']
}
}
```
## Require JS
**Important:** RequireJS [can **not** load CommonJS module as is](https://requirejs.org/docs/commonjs.html#intro), so be sure to require one of the UMD builds instead (i.e. `dist/Chart.js`, `dist/Chart.min.js`, etc.).
```javascript
require(['path/to/chartjs/dist/Chart.min.js'], function(Chart){
var myChart = new Chart(ctx, {...});
});
```
**Note:** starting v2.8, Moment.js is an optional dependency for `Chart.js` and `Chart.min.js`. In order to use the time scale with Moment.js, you need to make sure Moment.js is fully loaded **before** requiring Chart.js. You can either use a shim:
```javascript
require.config({
shim: {
'chartjs': {
deps: ['moment'] // enforce moment to be loaded before chartjs
}
},
paths: {
'chartjs': 'path/to/chartjs/dist/Chart.min.js',
'moment': 'path/to/moment'
}
});
require(['chartjs'], function(Chart) {
new Chart(ctx, {...});
});
```
or simply use two nested `require()`:
```javascript
require(['moment'], function() {
require(['chartjs'], function(Chart) {
new Chart(ctx, {...});
});
});
```
## Content Security Policy
By default, Chart.js injects CSS directly into the DOM. For webpages secured using [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), this requires to allow `style-src 'unsafe-inline'`. For stricter CSP environments, where only `style-src 'self'` is allowed, the following CSS file needs to be manually added to your webpage:
```html
<link rel="stylesheet" type="text/css" href="path/to/chartjs/dist/Chart.min.css">
```
And the style injection must be turned off **before creating the first chart**:
```javascript
// Disable automatic style injection
Chart.platform.disableCSSInjection = true;
```

View File

@@ -0,0 +1,65 @@
# Usage
Chart.js can be used with ES6 modules, plain JavaScript and module loaders.
## Creating a Chart
To create a chart, we need to instantiate the `Chart` class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart. Here's an example.
```html
<canvas id="myChart" width="400" height="400"></canvas>
```
```javascript
// Any of the following formats may be used
var ctx = document.getElementById('myChart');
var ctx = document.getElementById('myChart').getContext('2d');
var ctx = $('#myChart');
var ctx = 'myChart';
```
Once you have the element or context, you're ready to instantiate a pre-defined chart-type or create your own!
The following example instantiates a bar chart showing the number of votes for different colors and the y-axis starting at 0.
```html
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
```

View File

@@ -0,0 +1 @@
# Additional Notes

View File

@@ -0,0 +1,31 @@
# Comparison with Other Charting Libraries
Library Features
| Feature | Chart.js | D3 | HighCharts | Chartist |
| ------- | -------- | --- | ---------- | -------- |
| Completely Free | &check; | &check; | | &check; |
| Canvas | &check; | | | |
| SVG | | &check; | &check; | &check; |
| Built-in Charts | &check; | | &check; | &check; |
| 8+ Chart Types | &check; | &check; | &check; | |
| Extendable to Custom Charts | &check; | &check; | | |
| Supports Modern Browsers | &check; | &check; | &check; | &check; |
| Extensive Documentation | &check; | &check; | &check; | &check; |
| Open Source | &check; | &check; | | &check; |
Built in Chart Types
| Type | Chart.js | HighCharts | Chartist |
| ---- | -------- | ---------- | -------- |
| Combined Types | &check; | &check; | |
| Line | &check; | &check; | &check; |
| Bar | &check; | &check; | &check; |
| Horizontal Bar | &check; | &check; | &check; |
| Pie/Doughnut | &check; | &check; | &check; |
| Polar Area | &check; | &check; | |
| Radar | &check; | | |
| Scatter | &check; | &check; | &check; |
| Bubble | &check; | | |
| Gauges | | &check; | |
| Maps (Heat/Tree/etc.) | | &check; | |

View File

@@ -0,0 +1 @@
!REDIRECT "https://github.com/chartjs/awesome"

View File

@@ -0,0 +1,3 @@
# License
Chart.js is <a href="https://github.com/chartjs/Chart.js" target="_blank">open source</a> and available under the <a href="https://opensource.org/licenses/MIT" target="_blank">MIT license</a>.

View File

@@ -0,0 +1,15 @@
a.anchorjs-link {
color: rgba(65, 131, 196, 0.1);
font-weight: 400;
text-decoration: none;
transition: color 100ms ease-out;
z-index: 999;
}
a.anchorjs-link:hover {
color: rgba(65, 131, 196, 1);
}
sup {
font-size: 0.75em !important;
}

View File

@@ -0,0 +1,172 @@
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var file = require('gulp-file');
var replace = require('gulp-replace');
var size = require('gulp-size');
var streamify = require('gulp-streamify');
var terser = require('gulp-terser');
var zip = require('gulp-zip');
var exec = require('child_process').exec;
var karma = require('karma');
var merge = require('merge-stream');
var yargs = require('yargs');
var path = require('path');
var htmllint = require('gulp-htmllint');
var pkg = require('./package.json');
var argv = yargs
.option('verbose', {default: false})
.argv;
var srcDir = './src/';
var outDir = './dist/';
gulp.task('bower', bowerTask);
gulp.task('build', buildTask);
gulp.task('package', packageTask);
gulp.task('lint-html', lintHtmlTask);
gulp.task('lint-js', lintJsTask);
gulp.task('lint', gulp.parallel('lint-html', 'lint-js'));
gulp.task('docs', docsTask);
gulp.task('unittest', unittestTask);
gulp.task('test', gulp.parallel('lint', 'unittest'));
gulp.task('library-size', librarySizeTask);
gulp.task('module-sizes', moduleSizesTask);
gulp.task('size', gulp.parallel('library-size', 'module-sizes'));
gulp.task('default', gulp.parallel('build'));
function run(bin, args, done) {
return new Promise(function(resolve, reject) {
var exe = '"' + process.execPath + '"';
var src = require.resolve(bin);
var cmd = [exe, src].concat(args || []).join(' ');
var ps = exec(cmd);
ps.stdout.pipe(process.stdout);
ps.stderr.pipe(process.stderr);
ps.on('close', function(error) {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
/**
* Generates the bower.json manifest file which will be pushed along release tags.
* Specs: https://github.com/bower/spec/blob/master/json.md
*/
function bowerTask() {
var json = JSON.stringify({
name: pkg.name,
description: pkg.description,
homepage: pkg.homepage,
license: pkg.license,
version: pkg.version,
main: outDir + 'Chart.js',
ignore: [
'.github',
'.codeclimate.yml',
'.gitignore',
'.npmignore',
'.travis.yml',
'scripts'
]
}, null, 2);
return file('bower.json', json, { src: true })
.pipe(gulp.dest('./'));
}
function buildTask() {
return run('rollup/dist/bin/rollup', ['-c', argv.watch ? '--watch' : '']);
}
function packageTask() {
return merge(
// gather "regular" files landing in the package root
gulp.src([outDir + '*.js', outDir + '*.css', 'LICENSE.md']),
// since we moved the dist files one folder up (package root), we need to rewrite
// samples src="../dist/ to src="../ and then copy them in the /samples directory.
gulp.src('./samples/**/*', { base: '.' })
.pipe(streamify(replace(/src="((?:\.\.\/)+)dist\//g, 'src="$1')))
)
// finally, create the zip archive
.pipe(zip('Chart.js.zip'))
.pipe(gulp.dest(outDir));
}
function lintJsTask() {
var files = [
'samples/**/*.html',
'samples/**/*.js',
'src/**/*.js',
'test/**/*.js'
];
// NOTE(SB) codeclimate has 'complexity' and 'max-statements' eslint rules way too strict
// compare to what the current codebase can support, and since it's not straightforward
// to fix, let's turn them as warnings and rewrite code later progressively.
var options = {
rules: {
'complexity': [1, 10],
'max-statements': [1, 30]
}
};
return gulp.src(files)
.pipe(eslint(options))
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function lintHtmlTask() {
return gulp.src('samples/**/*.html')
.pipe(htmllint({
failOnError: true,
}));
}
function docsTask() {
var bin = 'gitbook-cli/bin/gitbook.js';
var cmd = argv.watch ? 'serve' : 'build';
return run(bin, ['install', './'])
.then(() => run(bin, [cmd, './', './dist/docs']));
}
function unittestTask(done) {
new karma.Server({
configFile: path.join(__dirname, 'karma.conf.js'),
singleRun: !argv.watch,
args: {
coverage: !!argv.coverage,
inputs: (argv.inputs || 'test/specs/**/*.js').split(';'),
watch: argv.watch
}
},
// https://github.com/karma-runner/gulp-karma/issues/18
function(error) {
error = error ? new Error('Karma returned with the error code: ' + error) : undefined;
done(error);
}).start();
}
function librarySizeTask() {
return gulp.src('dist/Chart.bundle.min.js')
.pipe(size({
gzip: true
}));
}
function moduleSizesTask() {
return gulp.src(srcDir + '**/*.js')
.pipe(terser())
.pipe(size({
showFiles: true,
gzip: true
}));
}

View File

@@ -0,0 +1,108 @@
/* eslint-env es6 */
const commonjs = require('rollup-plugin-commonjs');
const istanbul = require('rollup-plugin-istanbul');
const resolve = require('rollup-plugin-node-resolve');
const builds = require('./rollup.config');
module.exports = function(karma) {
const args = karma.args || {};
// Use the same rollup config as our dist files: when debugging (--watch),
// we will prefer the unminified build which is easier to browse and works
// better with source mapping. In other cases, pick the minified build to
// make sure that the minification process (terser) doesn't break anything.
const regex = args.watch ? /Chart\.js$/ : /Chart\.min\.js$/;
const build = builds.filter(v => v.output.file.match(regex))[0];
if (args.watch) {
build.output.sourcemap = 'inline';
}
karma.set({
frameworks: ['jasmine'],
reporters: ['progress', 'kjhtml'],
browsers: ['chrome', 'firefox'],
logLevel: karma.LOG_WARN,
// Explicitly disable hardware acceleration to make image
// diff more stable when ran on Travis and dev machine.
// https://github.com/chartjs/Chart.js/pull/5629
customLaunchers: {
chrome: {
base: 'Chrome',
flags: [
'--disable-accelerated-2d-canvas'
]
},
firefox: {
base: 'Firefox',
prefs: {
'layers.acceleration.disabled': true
}
}
},
files: [
{pattern: 'test/fixtures/**/*.js', included: false},
{pattern: 'test/fixtures/**/*.json', included: false},
{pattern: 'test/fixtures/**/*.png', included: false},
'node_modules/moment/min/moment.min.js',
'test/index.js',
'src/index.js'
].concat(args.inputs),
preprocessors: {
'test/index.js': ['rollup'],
'src/index.js': ['sources']
},
rollupPreprocessor: {
plugins: [
resolve(),
commonjs()
],
output: {
name: 'test',
format: 'umd'
}
},
customPreprocessors: {
sources: {
base: 'rollup',
options: build
}
},
// These settings deal with browser disconnects. We had seen test flakiness from Firefox
// [Firefox 56.0.0 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
// https://github.com/jasmine/jasmine/issues/1327#issuecomment-332939551
browserDisconnectTolerance: 3
});
// https://swizec.com/blog/how-to-run-javascript-tests-in-chrome-on-travis/swizec/6647
if (process.env.TRAVIS) {
karma.customLaunchers.chrome.flags.push('--no-sandbox');
}
if (args.coverage) {
karma.reporters.push('coverage');
karma.coverageReporter = {
dir: 'coverage/',
reporters: [
{type: 'html', subdir: 'html'},
{type: 'lcovonly', subdir: '.'}
]
};
[
karma.rollupPreprocessor,
karma.customPreprocessors.sources.options
].forEach(v => {
(v.plugins || (v.plugins = [])).unshift(
istanbul({
include: 'src/**/*.js'
}));
});
}
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,69 @@
{
"name": "chart.js",
"homepage": "https://www.chartjs.org",
"description": "Simple HTML5 charts using the canvas element.",
"version": "2.9.3",
"license": "MIT",
"jsdelivr": "dist/Chart.min.js",
"unpkg": "dist/Chart.min.js",
"main": "dist/Chart.js",
"keywords": [
"canvas",
"charts",
"data",
"graphs",
"html5",
"responsive"
],
"repository": {
"type": "git",
"url": "https://github.com/chartjs/Chart.js.git"
},
"bugs": {
"url": "https://github.com/chartjs/Chart.js/issues"
},
"files": [
"bower.json",
"composer.json",
"dist/*.css",
"dist/*.js"
],
"devDependencies": {
"clean-css": "^4.2.1",
"coveralls": "^3.0.0",
"eslint": "^5.9.0",
"eslint-config-chartjs": "^0.1.0",
"eslint-plugin-html": "^5.0.0",
"gitbook-cli": "^2.3.2",
"gulp": "^4.0.0",
"gulp-eslint": "^5.0.0",
"gulp-file": "^0.4.0",
"gulp-htmllint": "^0.0.16",
"gulp-replace": "^1.0.0",
"gulp-size": "^3.0.0",
"gulp-streamify": "^1.0.2",
"gulp-terser": "^1.1.6",
"gulp-zip": "^4.2.0",
"jasmine": "^3.3.0",
"jasmine-core": "^3.3.0",
"karma": "^4.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.1",
"karma-firefox-launcher": "^1.0.1",
"karma-jasmine": "^2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"karma-rollup-preprocessor": "^7.0.0",
"merge-stream": "^1.0.1",
"pixelmatch": "^4.0.2",
"rollup": "^1.0.0",
"rollup-plugin-commonjs": "^10.0.0",
"rollup-plugin-istanbul": "^2.0.1",
"rollup-plugin-node-resolve": "^5.0.0",
"rollup-plugin-terser": "^5.0.0",
"yargs": "^12.0.5"
},
"dependencies": {
"chartjs-color": "^2.1.0",
"moment": "^2.10.2"
}
}

View File

@@ -0,0 +1,119 @@
/* eslint-env es6 */
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
const terser = require('rollup-plugin-terser').terser;
const optional = require('./rollup.plugins').optional;
const stylesheet = require('./rollup.plugins').stylesheet;
const pkg = require('./package.json');
const input = 'src/index.js';
const banner = `/*!
* Chart.js v${pkg.version}
* ${pkg.homepage}
* (c) ${new Date().getFullYear()} Chart.js Contributors
* Released under the MIT License
*/`;
module.exports = [
// UMD builds (excluding moment)
// dist/Chart.min.js
// dist/Chart.js
{
input: input,
plugins: [
resolve(),
commonjs(),
stylesheet({
extract: true
}),
optional({
include: ['moment']
})
],
output: {
name: 'Chart',
file: 'dist/Chart.js',
banner: banner,
format: 'umd',
indent: false,
globals: {
moment: 'moment'
}
},
external: [
'moment'
]
},
{
input: input,
plugins: [
resolve(),
commonjs(),
optional({
include: ['moment']
}),
stylesheet({
extract: true,
minify: true
}),
terser({
output: {
preamble: banner
}
})
],
output: {
name: 'Chart',
file: 'dist/Chart.min.js',
format: 'umd',
indent: false,
globals: {
moment: 'moment'
}
},
external: [
'moment'
]
},
// UMD builds (including moment)
// dist/Chart.bundle.min.js
// dist/Chart.bundle.js
{
input: input,
plugins: [
resolve(),
commonjs(),
stylesheet()
],
output: {
name: 'Chart',
file: 'dist/Chart.bundle.js',
banner: banner,
format: 'umd',
indent: false
}
},
{
input: input,
plugins: [
resolve(),
commonjs(),
stylesheet({
minify: true
}),
terser({
output: {
preamble: banner
}
})
],
output: {
name: 'Chart',
file: 'dist/Chart.bundle.min.js',
format: 'umd',
indent: false
}
}
];

View File

@@ -0,0 +1,110 @@
/* eslint-env es6 */
const cleancss = require('clean-css');
const path = require('path');
const UMD_WRAPPER_RE = /(\(function \(global, factory\) \{)((?:\s.*?)*)(\}\(this,)/;
const CJS_FACTORY_RE = /(module.exports = )(factory\(.*?\))( :)/;
const AMD_FACTORY_RE = /(define\()(.*?, factory)(\) :)/;
function optional(config = {}) {
return {
name: 'optional',
renderChunk(code, chunk, options) {
if (options.format !== 'umd') {
this.error('only UMD format is currently supported');
}
const wrapper = UMD_WRAPPER_RE.exec(code);
const include = config.include;
if (!wrapper) {
this.error('failed to parse the UMD wrapper');
}
let content = wrapper[2];
let factory = (CJS_FACTORY_RE.exec(content) || [])[2];
let updated = false;
for (let lib of chunk.imports) {
if (!include || include.indexOf(lib) !== -1) {
const regex = new RegExp(`require\\('${lib}'\\)`);
if (!regex.test(factory)) {
this.error(`failed to parse the CJS require for ${lib}`);
}
// We need to write inline try / catch with explicit require
// in order to enable statical extraction of dependencies:
// try { return require('moment'); } catch(e) {}
const loader = `function() { try { return require('${lib}'); } catch(e) { } }()`;
factory = factory.replace(regex, loader);
updated = true;
}
}
if (!updated) {
return;
}
// Replace the CJS factory by our updated one.
content = content.replace(CJS_FACTORY_RE, `$1${factory}$3`);
// Replace the AMD factory by our updated one: we need to use the
// following AMD form in order to be able to try/catch require:
// define(['require'], function(require) { ... require(...); ... })
// https://github.com/amdjs/amdjs-api/wiki/AMD#using-require-and-exports
content = content.replace(AMD_FACTORY_RE, `$1['require'], function(require) { return ${factory}; }$3`);
return code.replace(UMD_WRAPPER_RE, `$1${content}$3`);
}
};
}
// https://github.com/chartjs/Chart.js/issues/5208
function stylesheet(config = {}) {
const minifier = new cleancss();
const styles = [];
return {
name: 'stylesheet',
transform(code, id) {
// Note that 'id' can be mapped to a CJS proxy import, in which case
// 'id' will start with 'commonjs-proxy', so let's first check if we
// are importing an existing css file (i.e. startsWith()).
if (!id.startsWith(path.resolve('.')) || !id.endsWith('.css')) {
return;
}
if (config.minify) {
code = minifier.minify(code).styles;
}
// keep track of all imported stylesheets (already minified)
styles.push(code);
return {
code: 'export default ' + JSON.stringify(code)
};
},
generateBundle(opts, bundle) {
if (!config.extract) {
return;
}
const entry = Object.keys(bundle).find(v => bundle[v].isEntry);
const name = (entry || '').replace(/\.js$/i, '.css');
if (!name) {
this.error('failed to guess the output file name');
}
this.emitFile({
type: 'asset',
source: styles.filter(v => !!v).join(''),
fileName: name
});
}
};
}
module.exports = {
optional,
stylesheet
};

View File

@@ -0,0 +1,72 @@
// TODO v3 - make this adapter external (chartjs-adapter-moment)
'use strict';
var moment = require('moment');
var adapters = require('../core/core.adapters');
var FORMATS = {
datetime: 'MMM D, YYYY, h:mm:ss a',
millisecond: 'h:mm:ss.SSS a',
second: 'h:mm:ss a',
minute: 'h:mm a',
hour: 'hA',
day: 'MMM D',
week: 'll',
month: 'MMM YYYY',
quarter: '[Q]Q - YYYY',
year: 'YYYY'
};
adapters._date.override(typeof moment === 'function' ? {
_id: 'moment', // DEBUG ONLY
formats: function() {
return FORMATS;
},
parse: function(value, format) {
if (typeof value === 'string' && typeof format === 'string') {
value = moment(value, format);
} else if (!(value instanceof moment)) {
value = moment(value);
}
return value.isValid() ? value.valueOf() : null;
},
format: function(time, format) {
return moment(time).format(format);
},
add: function(time, amount, unit) {
return moment(time).add(amount, unit).valueOf();
},
diff: function(max, min, unit) {
return moment(max).diff(moment(min), unit);
},
startOf: function(time, unit, weekday) {
time = moment(time);
if (unit === 'isoWeek') {
return time.isoWeekday(weekday).valueOf();
}
return time.startOf(unit).valueOf();
},
endOf: function(time, unit) {
return moment(time).endOf(unit).valueOf();
},
// DEPRECATIONS
/**
* Provided for backward compatibility with scale.getValueForPixel().
* @deprecated since version 2.8.0
* @todo remove at version 3
* @private
*/
_create: function(time) {
return moment(time);
},
} : {});

View File

@@ -0,0 +1,10 @@
'use strict';
// -----------------------------------------------------------------------------
// IMPORTANT: do NOT submit new adapters to this repository, instead
// create an external library named `chartjs-adapter-{lib-name}`
// -----------------------------------------------------------------------------
// Built-in moment adapter that we need to keep for backward compatibility
// https://github.com/chartjs/Chart.js/issues/5542
require('./adapter.moment');

View File

@@ -0,0 +1,431 @@
'use strict';
var DatasetController = require('../core/core.datasetController');
var defaults = require('../core/core.defaults');
var elements = require('../elements/index');
var helpers = require('../helpers/index');
var deprecated = helpers._deprecated;
var valueOrDefault = helpers.valueOrDefault;
defaults._set('bar', {
hover: {
mode: 'label'
},
scales: {
xAxes: [{
type: 'category',
offset: true,
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
type: 'linear'
}]
}
});
defaults._set('global', {
datasets: {
bar: {
categoryPercentage: 0.8,
barPercentage: 0.9
}
}
});
/**
* Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
* @private
*/
function computeMinSampleSize(scale, pixels) {
var min = scale._length;
var prev, curr, i, ilen;
for (i = 1, ilen = pixels.length; i < ilen; ++i) {
min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
}
for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
curr = scale.getPixelForTick(i);
min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
prev = curr;
}
return min;
}
/**
* Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
* uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
* mode currently always generates bars equally sized (until we introduce scriptable options?).
* @private
*/
function computeFitCategoryTraits(index, ruler, options) {
var thickness = options.barThickness;
var count = ruler.stackCount;
var curr = ruler.pixels[index];
var min = helpers.isNullOrUndef(thickness)
? computeMinSampleSize(ruler.scale, ruler.pixels)
: -1;
var size, ratio;
if (helpers.isNullOrUndef(thickness)) {
size = min * options.categoryPercentage;
ratio = options.barPercentage;
} else {
// When bar thickness is enforced, category and bar percentages are ignored.
// Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
// and deprecate barPercentage since this value is ignored when thickness is absolute.
size = thickness * count;
ratio = 1;
}
return {
chunk: size / count,
ratio: ratio,
start: curr - (size / 2)
};
}
/**
* Computes an "optimal" category that globally arranges bars side by side (no gap when
* percentage options are 1), based on the previous and following categories. This mode
* generates bars with different widths when data are not evenly spaced.
* @private
*/
function computeFlexCategoryTraits(index, ruler, options) {
var pixels = ruler.pixels;
var curr = pixels[index];
var prev = index > 0 ? pixels[index - 1] : null;
var next = index < pixels.length - 1 ? pixels[index + 1] : null;
var percent = options.categoryPercentage;
var start, size;
if (prev === null) {
// first data: its size is double based on the next point or,
// if it's also the last data, we use the scale size.
prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
}
if (next === null) {
// last data: its size is also double based on the previous point.
next = curr + curr - prev;
}
start = curr - (curr - Math.min(prev, next)) / 2 * percent;
size = Math.abs(next - prev) / 2 * percent;
return {
chunk: size / ruler.stackCount,
ratio: options.barPercentage,
start: start
};
}
module.exports = DatasetController.extend({
dataElementType: elements.Rectangle,
/**
* @private
*/
_dataElementOptions: [
'backgroundColor',
'borderColor',
'borderSkipped',
'borderWidth',
'barPercentage',
'barThickness',
'categoryPercentage',
'maxBarThickness',
'minBarLength'
],
initialize: function() {
var me = this;
var meta, scaleOpts;
DatasetController.prototype.initialize.apply(me, arguments);
meta = me.getMeta();
meta.stack = me.getDataset().stack;
meta.bar = true;
scaleOpts = me._getIndexScale().options;
deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
},
update: function(reset) {
var me = this;
var rects = me.getMeta().data;
var i, ilen;
me._ruler = me.getRuler();
for (i = 0, ilen = rects.length; i < ilen; ++i) {
me.updateElement(rects[i], i, reset);
}
},
updateElement: function(rectangle, index, reset) {
var me = this;
var meta = me.getMeta();
var dataset = me.getDataset();
var options = me._resolveDataElementOptions(rectangle, index);
rectangle._xScale = me.getScaleForId(meta.xAxisID);
rectangle._yScale = me.getScaleForId(meta.yAxisID);
rectangle._datasetIndex = me.index;
rectangle._index = index;
rectangle._model = {
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderSkipped: options.borderSkipped,
borderWidth: options.borderWidth,
datasetLabel: dataset.label,
label: me.chart.data.labels[index]
};
if (helpers.isArray(dataset.data[index])) {
rectangle._model.borderSkipped = null;
}
me._updateElementGeometry(rectangle, index, reset, options);
rectangle.pivot();
},
/**
* @private
*/
_updateElementGeometry: function(rectangle, index, reset, options) {
var me = this;
var model = rectangle._model;
var vscale = me._getValueScale();
var base = vscale.getBasePixel();
var horizontal = vscale.isHorizontal();
var ruler = me._ruler || me.getRuler();
var vpixels = me.calculateBarValuePixels(me.index, index, options);
var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
model.horizontal = horizontal;
model.base = reset ? base : vpixels.base;
model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
model.height = horizontal ? ipixels.size : undefined;
model.width = horizontal ? undefined : ipixels.size;
},
/**
* Returns the stacks based on groups and bar visibility.
* @param {number} [last] - The dataset index
* @returns {string[]} The list of stack IDs
* @private
*/
_getStacks: function(last) {
var me = this;
var scale = me._getIndexScale();
var metasets = scale._getMatchingVisibleMetas(me._type);
var stacked = scale.options.stacked;
var ilen = metasets.length;
var stacks = [];
var i, meta;
for (i = 0; i < ilen; ++i) {
meta = metasets[i];
// stacked | meta.stack
// | found | not found | undefined
// false | x | x | x
// true | | x |
// undefined | | x | x
if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
(stacked === undefined && meta.stack === undefined)) {
stacks.push(meta.stack);
}
if (meta.index === last) {
break;
}
}
return stacks;
},
/**
* Returns the effective number of stacks based on groups and bar visibility.
* @private
*/
getStackCount: function() {
return this._getStacks().length;
},
/**
* Returns the stack index for the given dataset based on groups and bar visibility.
* @param {number} [datasetIndex] - The dataset index
* @param {string} [name] - The stack name to find
* @returns {number} The stack index
* @private
*/
getStackIndex: function(datasetIndex, name) {
var stacks = this._getStacks(datasetIndex);
var index = (name !== undefined)
? stacks.indexOf(name)
: -1; // indexOf returns -1 if element is not present
return (index === -1)
? stacks.length - 1
: index;
},
/**
* @private
*/
getRuler: function() {
var me = this;
var scale = me._getIndexScale();
var pixels = [];
var i, ilen;
for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
pixels.push(scale.getPixelForValue(null, i, me.index));
}
return {
pixels: pixels,
start: scale._startPixel,
end: scale._endPixel,
stackCount: me.getStackCount(),
scale: scale
};
},
/**
* Note: pixel values are not clamped to the scale area.
* @private
*/
calculateBarValuePixels: function(datasetIndex, index, options) {
var me = this;
var chart = me.chart;
var scale = me._getValueScale();
var isHorizontal = scale.isHorizontal();
var datasets = chart.data.datasets;
var metasets = scale._getMatchingVisibleMetas(me._type);
var value = scale._parseValue(datasets[datasetIndex].data[index]);
var minBarLength = options.minBarLength;
var stacked = scale.options.stacked;
var stack = me.getMeta().stack;
var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
var ilen = metasets.length;
var i, imeta, ivalue, base, head, size, stackLength;
if (stacked || (stacked === undefined && stack !== undefined)) {
for (i = 0; i < ilen; ++i) {
imeta = metasets[i];
if (imeta.index === datasetIndex) {
break;
}
if (imeta.stack === stack) {
stackLength = scale._parseValue(datasets[imeta.index].data[index]);
ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
start += ivalue;
}
}
}
}
base = scale.getPixelForValue(start);
head = scale.getPixelForValue(start + length);
size = head - base;
if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
size = minBarLength;
if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
head = base - minBarLength;
} else {
head = base + minBarLength;
}
}
return {
size: size,
base: base,
head: head,
center: head + size / 2
};
},
/**
* @private
*/
calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
var me = this;
var range = options.barThickness === 'flex'
? computeFlexCategoryTraits(index, ruler, options)
: computeFitCategoryTraits(index, ruler, options);
var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
var size = Math.min(
valueOrDefault(options.maxBarThickness, Infinity),
range.chunk * range.ratio);
return {
base: center - size / 2,
head: center + size / 2,
center: center,
size: size
};
},
draw: function() {
var me = this;
var chart = me.chart;
var scale = me._getValueScale();
var rects = me.getMeta().data;
var dataset = me.getDataset();
var ilen = rects.length;
var i = 0;
helpers.canvas.clipArea(chart.ctx, chart.chartArea);
for (; i < ilen; ++i) {
var val = scale._parseValue(dataset.data[i]);
if (!isNaN(val.min) && !isNaN(val.max)) {
rects[i].draw();
}
}
helpers.canvas.unclipArea(chart.ctx);
},
/**
* @private
*/
_resolveDataElementOptions: function() {
var me = this;
var values = helpers.extend({}, DatasetController.prototype._resolveDataElementOptions.apply(me, arguments));
var indexOpts = me._getIndexScale().options;
var valueOpts = me._getValueScale().options;
values.barPercentage = valueOrDefault(indexOpts.barPercentage, values.barPercentage);
values.barThickness = valueOrDefault(indexOpts.barThickness, values.barThickness);
values.categoryPercentage = valueOrDefault(indexOpts.categoryPercentage, values.categoryPercentage);
values.maxBarThickness = valueOrDefault(indexOpts.maxBarThickness, values.maxBarThickness);
values.minBarLength = valueOrDefault(valueOpts.minBarLength, values.minBarLength);
return values;
}
});

View File

@@ -0,0 +1,172 @@
'use strict';
var DatasetController = require('../core/core.datasetController');
var defaults = require('../core/core.defaults');
var elements = require('../elements/index');
var helpers = require('../helpers/index');
var valueOrDefault = helpers.valueOrDefault;
var resolve = helpers.options.resolve;
defaults._set('bubble', {
hover: {
mode: 'single'
},
scales: {
xAxes: [{
type: 'linear', // bubble should probably use a linear scale by default
position: 'bottom',
id: 'x-axis-0' // need an ID so datasets can reference the scale
}],
yAxes: [{
type: 'linear',
position: 'left',
id: 'y-axis-0'
}]
},
tooltips: {
callbacks: {
title: function() {
// Title doesn't make sense for scatter since we format the data as a point
return '';
},
label: function(item, data) {
var datasetLabel = data.datasets[item.datasetIndex].label || '';
var dataPoint = data.datasets[item.datasetIndex].data[item.index];
return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
}
}
}
});
module.exports = DatasetController.extend({
/**
* @protected
*/
dataElementType: elements.Point,
/**
* @private
*/
_dataElementOptions: [
'backgroundColor',
'borderColor',
'borderWidth',
'hoverBackgroundColor',
'hoverBorderColor',
'hoverBorderWidth',
'hoverRadius',
'hitRadius',
'pointStyle',
'rotation'
],
/**
* @protected
*/
update: function(reset) {
var me = this;
var meta = me.getMeta();
var points = meta.data;
// Update Points
helpers.each(points, function(point, index) {
me.updateElement(point, index, reset);
});
},
/**
* @protected
*/
updateElement: function(point, index, reset) {
var me = this;
var meta = me.getMeta();
var custom = point.custom || {};
var xScale = me.getScaleForId(meta.xAxisID);
var yScale = me.getScaleForId(meta.yAxisID);
var options = me._resolveDataElementOptions(point, index);
var data = me.getDataset().data[index];
var dsIndex = me.index;
var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
point._xScale = xScale;
point._yScale = yScale;
point._options = options;
point._datasetIndex = dsIndex;
point._index = index;
point._model = {
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
hitRadius: options.hitRadius,
pointStyle: options.pointStyle,
rotation: options.rotation,
radius: reset ? 0 : options.radius,
skip: custom.skip || isNaN(x) || isNaN(y),
x: x,
y: y,
};
point.pivot();
},
/**
* @protected
*/
setHoverStyle: function(point) {
var model = point._model;
var options = point._options;
var getHoverColor = helpers.getHoverColor;
point.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
radius: model.radius
};
model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
model.radius = options.radius + options.hoverRadius;
},
/**
* @private
*/
_resolveDataElementOptions: function(point, index) {
var me = this;
var chart = me.chart;
var dataset = me.getDataset();
var custom = point.custom || {};
var data = dataset.data[index] || {};
var values = DatasetController.prototype._resolveDataElementOptions.apply(me, arguments);
// Scriptable options
var context = {
chart: chart,
dataIndex: index,
dataset: dataset,
datasetIndex: me.index
};
// In case values were cached (and thus frozen), we need to clone the values
if (me._cachedDataOpts === values) {
values = helpers.extend({}, values);
}
// Custom radius resolution
values.radius = resolve([
custom.radius,
data.r,
me._config.radius,
chart.options.elements.point.radius
], context, index);
return values;
}
});

View File

@@ -0,0 +1,390 @@
'use strict';
var DatasetController = require('../core/core.datasetController');
var defaults = require('../core/core.defaults');
var elements = require('../elements/index');
var helpers = require('../helpers/index');
var valueOrDefault = helpers.valueOrDefault;
var PI = Math.PI;
var DOUBLE_PI = PI * 2;
var HALF_PI = PI / 2;
defaults._set('doughnut', {
animation: {
// Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
// Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false
},
hover: {
mode: 'single'
},
legendCallback: function(chart) {
var list = document.createElement('ul');
var data = chart.data;
var datasets = data.datasets;
var labels = data.labels;
var i, ilen, listItem, listItemSpan;
list.setAttribute('class', chart.id + '-legend');
if (datasets.length) {
for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
listItem = list.appendChild(document.createElement('li'));
listItemSpan = listItem.appendChild(document.createElement('span'));
listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
if (labels[i]) {
listItem.appendChild(document.createTextNode(labels[i]));
}
}
}
return list.outerHTML;
},
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var style = meta.controller.getStyle(i);
return {
text: label,
fillStyle: style.backgroundColor,
strokeStyle: style.borderColor,
lineWidth: style.borderWidth,
hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
// Extra data used for toggling the correct item
index: i
};
});
}
return [];
}
},
onClick: function(e, legendItem) {
var index = legendItem.index;
var chart = this.chart;
var i, ilen, meta;
for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
// toggle visibility of index if exists
if (meta.data[index]) {
meta.data[index].hidden = !meta.data[index].hidden;
}
}
chart.update();
}
},
// The percentage of the chart that we cut out of the middle.
cutoutPercentage: 50,
// The rotation of the chart, where the first data arc begins.
rotation: -HALF_PI,
// The total circumference of the chart.
circumference: DOUBLE_PI,
// Need to override these to give a nice default
tooltips: {
callbacks: {
title: function() {
return '';
},
label: function(tooltipItem, data) {
var dataLabel = data.labels[tooltipItem.index];
var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
if (helpers.isArray(dataLabel)) {
// show value on first line of multiline label
// need to clone because we are changing the value
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
return dataLabel;
}
}
}
});
module.exports = DatasetController.extend({
dataElementType: elements.Arc,
linkScales: helpers.noop,
/**
* @private
*/
_dataElementOptions: [
'backgroundColor',
'borderColor',
'borderWidth',
'borderAlign',
'hoverBackgroundColor',
'hoverBorderColor',
'hoverBorderWidth',
],
// Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
getRingIndex: function(datasetIndex) {
var ringIndex = 0;
for (var j = 0; j < datasetIndex; ++j) {
if (this.chart.isDatasetVisible(j)) {
++ringIndex;
}
}
return ringIndex;
},
update: function(reset) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var ratioX = 1;
var ratioY = 1;
var offsetX = 0;
var offsetY = 0;
var meta = me.getMeta();
var arcs = meta.data;
var cutout = opts.cutoutPercentage / 100 || 0;
var circumference = opts.circumference;
var chartWeight = me._getRingWeight(me.index);
var maxWidth, maxHeight, i, ilen;
// If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
if (circumference < DOUBLE_PI) {
var startAngle = opts.rotation % DOUBLE_PI;
startAngle += startAngle >= PI ? -DOUBLE_PI : startAngle < -PI ? DOUBLE_PI : 0;
var endAngle = startAngle + circumference;
var startX = Math.cos(startAngle);
var startY = Math.sin(startAngle);
var endX = Math.cos(endAngle);
var endY = Math.sin(endAngle);
var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI;
var contains90 = (startAngle <= HALF_PI && endAngle >= HALF_PI) || endAngle >= DOUBLE_PI + HALF_PI;
var contains180 = startAngle === -PI || endAngle >= PI;
var contains270 = (startAngle <= -HALF_PI && endAngle >= -HALF_PI) || endAngle >= PI + HALF_PI;
var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
ratioX = (maxX - minX) / 2;
ratioY = (maxY - minY) / 2;
offsetX = -(maxX + minX) / 2;
offsetY = -(maxY + minY) / 2;
}
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
}
chart.borderWidth = me.getMaxBorderWidth();
maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
chart.offsetX = offsetX * chart.outerRadius;
chart.offsetY = offsetY * chart.outerRadius;
meta.total = me.calculateTotal();
me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
me.updateElement(arcs[i], i, reset);
}
},
updateElement: function(arc, index, reset) {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var animationOpts = opts.animation;
var centerX = (chartArea.left + chartArea.right) / 2;
var centerY = (chartArea.top + chartArea.bottom) / 2;
var startAngle = opts.rotation; // non reset case handled later
var endAngle = opts.rotation; // non reset case handled later
var dataset = me.getDataset();
var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI);
var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
var options = arc._options || {};
helpers.extend(arc, {
// Utility
_datasetIndex: me.index,
_index: index,
// Desired view properties
_model: {
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
borderAlign: options.borderAlign,
x: centerX + chart.offsetX,
y: centerY + chart.offsetY,
startAngle: startAngle,
endAngle: endAngle,
circumference: circumference,
outerRadius: outerRadius,
innerRadius: innerRadius,
label: helpers.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
}
});
var model = arc._model;
// Set correct angles if not resetting
if (!reset || !animationOpts.animateRotate) {
if (index === 0) {
model.startAngle = opts.rotation;
} else {
model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
}
model.endAngle = model.startAngle + model.circumference;
}
arc.pivot();
},
calculateTotal: function() {
var dataset = this.getDataset();
var meta = this.getMeta();
var total = 0;
var value;
helpers.each(meta.data, function(element, index) {
value = dataset.data[index];
if (!isNaN(value) && !element.hidden) {
total += Math.abs(value);
}
});
/* if (total === 0) {
total = NaN;
}*/
return total;
},
calculateCircumference: function(value) {
var total = this.getMeta().total;
if (total > 0 && !isNaN(value)) {
return DOUBLE_PI * (Math.abs(value) / total);
}
return 0;
},
// gets the max border or hover width to properly scale pie charts
getMaxBorderWidth: function(arcs) {
var me = this;
var max = 0;
var chart = me.chart;
var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
if (!arcs) {
// Find the outmost visible dataset
for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
if (chart.isDatasetVisible(i)) {
meta = chart.getDatasetMeta(i);
arcs = meta.data;
if (i !== me.index) {
controller = meta.controller;
}
break;
}
}
}
if (!arcs) {
return 0;
}
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
arc = arcs[i];
if (controller) {
controller._configure();
options = controller._resolveDataElementOptions(arc, i);
} else {
options = arc._options;
}
if (options.borderAlign !== 'inner') {
borderWidth = options.borderWidth;
hoverWidth = options.hoverBorderWidth;
max = borderWidth > max ? borderWidth : max;
max = hoverWidth > max ? hoverWidth : max;
}
}
return max;
},
/**
* @protected
*/
setHoverStyle: function(arc) {
var model = arc._model;
var options = arc._options;
var getHoverColor = helpers.getHoverColor;
arc.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
};
model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
},
/**
* Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
* @private
*/
_getRingWeightOffset: function(datasetIndex) {
var ringWeightOffset = 0;
for (var i = 0; i < datasetIndex; ++i) {
if (this.chart.isDatasetVisible(i)) {
ringWeightOffset += this._getRingWeight(i);
}
}
return ringWeightOffset;
},
/**
* @private
*/
_getRingWeight: function(dataSetIndex) {
return Math.max(valueOrDefault(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
},
/**
* Returns the sum of all visibile data set weights. This value can be 0.
* @private
*/
_getVisibleDatasetWeightTotal: function() {
return this._getRingWeightOffset(this.chart.data.datasets.length);
}
});

View File

@@ -0,0 +1,63 @@
'use strict';
var BarController = require('./controller.bar');
var defaults = require('../core/core.defaults');
defaults._set('horizontalBar', {
hover: {
mode: 'index',
axis: 'y'
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}],
yAxes: [{
type: 'category',
position: 'left',
offset: true,
gridLines: {
offsetGridLines: true
}
}]
},
elements: {
rectangle: {
borderSkipped: 'left'
}
},
tooltips: {
mode: 'index',
axis: 'y'
}
});
defaults._set('global', {
datasets: {
horizontalBar: {
categoryPercentage: 0.8,
barPercentage: 0.9
}
}
});
module.exports = BarController.extend({
/**
* @private
*/
_getValueScaleId: function() {
return this.getMeta().xAxisID;
},
/**
* @private
*/
_getIndexScaleId: function() {
return this.getMeta().yAxisID;
}
});

View File

@@ -0,0 +1,371 @@
'use strict';
var DatasetController = require('../core/core.datasetController');
var defaults = require('../core/core.defaults');
var elements = require('../elements/index');
var helpers = require('../helpers/index');
var valueOrDefault = helpers.valueOrDefault;
var resolve = helpers.options.resolve;
var isPointInArea = helpers.canvas._isPointInArea;
defaults._set('line', {
showLines: true,
spanGaps: false,
hover: {
mode: 'label'
},
scales: {
xAxes: [{
type: 'category',
id: 'x-axis-0'
}],
yAxes: [{
type: 'linear',
id: 'y-axis-0'
}]
}
});
function scaleClip(scale, halfBorderWidth) {
var tickOpts = scale && scale.options.ticks || {};
var reverse = tickOpts.reverse;
var min = tickOpts.min === undefined ? halfBorderWidth : 0;
var max = tickOpts.max === undefined ? halfBorderWidth : 0;
return {
start: reverse ? max : min,
end: reverse ? min : max
};
}
function defaultClip(xScale, yScale, borderWidth) {
var halfBorderWidth = borderWidth / 2;
var x = scaleClip(xScale, halfBorderWidth);
var y = scaleClip(yScale, halfBorderWidth);
return {
top: y.end,
right: x.end,
bottom: y.start,
left: x.start
};
}
function toClip(value) {
var t, r, b, l;
if (helpers.isObject(value)) {
t = value.top;
r = value.right;
b = value.bottom;
l = value.left;
} else {
t = r = b = l = value;
}
return {
top: t,
right: r,
bottom: b,
left: l
};
}
module.exports = DatasetController.extend({
datasetElementType: elements.Line,
dataElementType: elements.Point,
/**
* @private
*/
_datasetElementOptions: [
'backgroundColor',
'borderCapStyle',
'borderColor',
'borderDash',
'borderDashOffset',
'borderJoinStyle',
'borderWidth',
'cubicInterpolationMode',
'fill'
],
/**
* @private
*/
_dataElementOptions: {
backgroundColor: 'pointBackgroundColor',
borderColor: 'pointBorderColor',
borderWidth: 'pointBorderWidth',
hitRadius: 'pointHitRadius',
hoverBackgroundColor: 'pointHoverBackgroundColor',
hoverBorderColor: 'pointHoverBorderColor',
hoverBorderWidth: 'pointHoverBorderWidth',
hoverRadius: 'pointHoverRadius',
pointStyle: 'pointStyle',
radius: 'pointRadius',
rotation: 'pointRotation'
},
update: function(reset) {
var me = this;
var meta = me.getMeta();
var line = meta.dataset;
var points = meta.data || [];
var options = me.chart.options;
var config = me._config;
var showLine = me._showLine = valueOrDefault(config.showLine, options.showLines);
var i, ilen;
me._xScale = me.getScaleForId(meta.xAxisID);
me._yScale = me.getScaleForId(meta.yAxisID);
// Update Line
if (showLine) {
// Compatibility: If the properties are defined with only the old name, use those values
if (config.tension !== undefined && config.lineTension === undefined) {
config.lineTension = config.tension;
}
// Utility
line._scale = me._yScale;
line._datasetIndex = me.index;
// Data
line._children = points;
// Model
line._model = me._resolveDatasetElementOptions(line);
line.pivot();
}
// Update Points
for (i = 0, ilen = points.length; i < ilen; ++i) {
me.updateElement(points[i], i, reset);
}
if (showLine && line._model.tension !== 0) {
me.updateBezierControlPoints();
}
// Now pivot the point for animation
for (i = 0, ilen = points.length; i < ilen; ++i) {
points[i].pivot();
}
},
updateElement: function(point, index, reset) {
var me = this;
var meta = me.getMeta();
var custom = point.custom || {};
var dataset = me.getDataset();
var datasetIndex = me.index;
var value = dataset.data[index];
var xScale = me._xScale;
var yScale = me._yScale;
var lineModel = meta.dataset._model;
var x, y;
var options = me._resolveDataElementOptions(point, index);
x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
// Utility
point._xScale = xScale;
point._yScale = yScale;
point._options = options;
point._datasetIndex = datasetIndex;
point._index = index;
// Desired view properties
point._model = {
x: x,
y: y,
skip: custom.skip || isNaN(x) || isNaN(y),
// Appearance
radius: options.radius,
pointStyle: options.pointStyle,
rotation: options.rotation,
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
tension: valueOrDefault(custom.tension, lineModel ? lineModel.tension : 0),
steppedLine: lineModel ? lineModel.steppedLine : false,
// Tooltip
hitRadius: options.hitRadius
};
},
/**
* @private
*/
_resolveDatasetElementOptions: function(element) {
var me = this;
var config = me._config;
var custom = element.custom || {};
var options = me.chart.options;
var lineOptions = options.elements.line;
var values = DatasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
// The default behavior of lines is to break at null values, according
// to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
// This option gives lines the ability to span gaps
values.spanGaps = valueOrDefault(config.spanGaps, options.spanGaps);
values.tension = valueOrDefault(config.lineTension, lineOptions.tension);
values.steppedLine = resolve([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
values.clip = toClip(valueOrDefault(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
return values;
},
calculatePointY: function(value, index, datasetIndex) {
var me = this;
var chart = me.chart;
var yScale = me._yScale;
var sumPos = 0;
var sumNeg = 0;
var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
if (yScale.options.stacked) {
rightValue = +yScale.getRightValue(value);
metasets = chart._getSortedVisibleDatasetMetas();
ilen = metasets.length;
for (i = 0; i < ilen; ++i) {
dsMeta = metasets[i];
if (dsMeta.index === datasetIndex) {
break;
}
ds = chart.data.datasets[dsMeta.index];
if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
stackedRightValue = +yScale.getRightValue(ds.data[index]);
if (stackedRightValue < 0) {
sumNeg += stackedRightValue || 0;
} else {
sumPos += stackedRightValue || 0;
}
}
}
if (rightValue < 0) {
return yScale.getPixelForValue(sumNeg + rightValue);
}
return yScale.getPixelForValue(sumPos + rightValue);
}
return yScale.getPixelForValue(value);
},
updateBezierControlPoints: function() {
var me = this;
var chart = me.chart;
var meta = me.getMeta();
var lineModel = meta.dataset._model;
var area = chart.chartArea;
var points = meta.data || [];
var i, ilen, model, controlPoints;
// Only consider points that are drawn in case the spanGaps option is used
if (lineModel.spanGaps) {
points = points.filter(function(pt) {
return !pt._model.skip;
});
}
function capControlPoint(pt, min, max) {
return Math.max(Math.min(pt, max), min);
}
if (lineModel.cubicInterpolationMode === 'monotone') {
helpers.splineCurveMonotone(points);
} else {
for (i = 0, ilen = points.length; i < ilen; ++i) {
model = points[i]._model;
controlPoints = helpers.splineCurve(
helpers.previousItem(points, i)._model,
model,
helpers.nextItem(points, i)._model,
lineModel.tension
);
model.controlPointPreviousX = controlPoints.previous.x;
model.controlPointPreviousY = controlPoints.previous.y;
model.controlPointNextX = controlPoints.next.x;
model.controlPointNextY = controlPoints.next.y;
}
}
if (chart.options.elements.line.capBezierPoints) {
for (i = 0, ilen = points.length; i < ilen; ++i) {
model = points[i]._model;
if (isPointInArea(model, area)) {
if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
}
if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
}
}
}
}
},
draw: function() {
var me = this;
var chart = me.chart;
var meta = me.getMeta();
var points = meta.data || [];
var area = chart.chartArea;
var canvas = chart.canvas;
var i = 0;
var ilen = points.length;
var clip;
if (me._showLine) {
clip = meta.dataset._model.clip;
helpers.canvas.clipArea(chart.ctx, {
left: clip.left === false ? 0 : area.left - clip.left,
right: clip.right === false ? canvas.width : area.right + clip.right,
top: clip.top === false ? 0 : area.top - clip.top,
bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
});
meta.dataset.draw();
helpers.canvas.unclipArea(chart.ctx);
}
// Draw the points
for (; i < ilen; ++i) {
points[i].draw(area);
}
},
/**
* @protected
*/
setHoverStyle: function(point) {
var model = point._model;
var options = point._options;
var getHoverColor = helpers.getHoverColor;
point.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
radius: model.radius
};
model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
model.radius = valueOrDefault(options.hoverRadius, options.radius);
},
});

View File

@@ -0,0 +1,13 @@
'use strict';
var DoughnutController = require('./controller.doughnut');
var defaults = require('../core/core.defaults');
var helpers = require('../helpers/index');
defaults._set('pie', helpers.clone(defaults.doughnut));
defaults._set('pie', {
cutoutPercentage: 0
});
// Pie charts are Doughnut chart with different defaults
module.exports = DoughnutController;

View File

@@ -0,0 +1,291 @@
'use strict';
var DatasetController = require('../core/core.datasetController');
var defaults = require('../core/core.defaults');
var elements = require('../elements/index');
var helpers = require('../helpers/index');
var resolve = helpers.options.resolve;
defaults._set('polarArea', {
scale: {
type: 'radialLinear',
angleLines: {
display: false
},
gridLines: {
circular: true
},
pointLabels: {
display: false
},
ticks: {
beginAtZero: true
}
},
// Boolean - Whether to animate the rotation of the chart
animation: {
animateRotate: true,
animateScale: true
},
startAngle: -0.5 * Math.PI,
legendCallback: function(chart) {
var list = document.createElement('ul');
var data = chart.data;
var datasets = data.datasets;
var labels = data.labels;
var i, ilen, listItem, listItemSpan;
list.setAttribute('class', chart.id + '-legend');
if (datasets.length) {
for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
listItem = list.appendChild(document.createElement('li'));
listItemSpan = listItem.appendChild(document.createElement('span'));
listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
if (labels[i]) {
listItem.appendChild(document.createTextNode(labels[i]));
}
}
}
return list.outerHTML;
},
legend: {
labels: {
generateLabels: function(chart) {
var data = chart.data;
if (data.labels.length && data.datasets.length) {
return data.labels.map(function(label, i) {
var meta = chart.getDatasetMeta(0);
var style = meta.controller.getStyle(i);
return {
text: label,
fillStyle: style.backgroundColor,
strokeStyle: style.borderColor,
lineWidth: style.borderWidth,
hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
// Extra data used for toggling the correct item
index: i
};
});
}
return [];
}
},
onClick: function(e, legendItem) {
var index = legendItem.index;
var chart = this.chart;
var i, ilen, meta;
for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i);
meta.data[index].hidden = !meta.data[index].hidden;
}
chart.update();
}
},
// Need to override these to give a nice default
tooltips: {
callbacks: {
title: function() {
return '';
},
label: function(item, data) {
return data.labels[item.index] + ': ' + item.yLabel;
}
}
}
});
module.exports = DatasetController.extend({
dataElementType: elements.Arc,
linkScales: helpers.noop,
/**
* @private
*/
_dataElementOptions: [
'backgroundColor',
'borderColor',
'borderWidth',
'borderAlign',
'hoverBackgroundColor',
'hoverBorderColor',
'hoverBorderWidth',
],
/**
* @private
*/
_getIndexScaleId: function() {
return this.chart.scale.id;
},
/**
* @private
*/
_getValueScaleId: function() {
return this.chart.scale.id;
},
update: function(reset) {
var me = this;
var dataset = me.getDataset();
var meta = me.getMeta();
var start = me.chart.options.startAngle || 0;
var starts = me._starts = [];
var angles = me._angles = [];
var arcs = meta.data;
var i, ilen, angle;
me._updateRadius();
meta.count = me.countVisibleElements();
for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
starts[i] = start;
angle = me._computeAngle(i);
angles[i] = angle;
start += angle;
}
for (i = 0, ilen = arcs.length; i < ilen; ++i) {
arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
me.updateElement(arcs[i], i, reset);
}
},
/**
* @private
*/
_updateRadius: function() {
var me = this;
var chart = me.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
chart.outerRadius = Math.max(minSize / 2, 0);
chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
me.innerRadius = me.outerRadius - chart.radiusLength;
},
updateElement: function(arc, index, reset) {
var me = this;
var chart = me.chart;
var dataset = me.getDataset();
var opts = chart.options;
var animationOpts = opts.animation;
var scale = chart.scale;
var labels = chart.data.labels;
var centerX = scale.xCenter;
var centerY = scale.yCenter;
// var negHalfPI = -0.5 * Math.PI;
var datasetStartAngle = opts.startAngle;
var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
var startAngle = me._starts[index];
var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
var options = arc._options || {};
helpers.extend(arc, {
// Utility
_datasetIndex: me.index,
_index: index,
_scale: scale,
// Desired view properties
_model: {
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
borderAlign: options.borderAlign,
x: centerX,
y: centerY,
innerRadius: 0,
outerRadius: reset ? resetRadius : distance,
startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
label: helpers.valueAtIndexOrDefault(labels, index, labels[index])
}
});
arc.pivot();
},
countVisibleElements: function() {
var dataset = this.getDataset();
var meta = this.getMeta();
var count = 0;
helpers.each(meta.data, function(element, index) {
if (!isNaN(dataset.data[index]) && !element.hidden) {
count++;
}
});
return count;
},
/**
* @protected
*/
setHoverStyle: function(arc) {
var model = arc._model;
var options = arc._options;
var getHoverColor = helpers.getHoverColor;
var valueOrDefault = helpers.valueOrDefault;
arc.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
};
model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
},
/**
* @private
*/
_computeAngle: function(index) {
var me = this;
var count = this.getMeta().count;
var dataset = me.getDataset();
var meta = me.getMeta();
if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
return 0;
}
// Scriptable options
var context = {
chart: me.chart,
dataIndex: index,
dataset: dataset,
datasetIndex: me.index
};
return resolve([
me.chart.options.elements.arc.angle,
(2 * Math.PI) / count
], context, index);
}
});

View File

@@ -0,0 +1,217 @@
'use strict';
var DatasetController = require('../core/core.datasetController');
var defaults = require('../core/core.defaults');
var elements = require('../elements/index');
var helpers = require('../helpers/index');
var valueOrDefault = helpers.valueOrDefault;
defaults._set('radar', {
spanGaps: false,
scale: {
type: 'radialLinear'
},
elements: {
line: {
fill: 'start',
tension: 0 // no bezier in radar
}
}
});
module.exports = DatasetController.extend({
datasetElementType: elements.Line,
dataElementType: elements.Point,
linkScales: helpers.noop,
/**
* @private
*/
_datasetElementOptions: [
'backgroundColor',
'borderWidth',
'borderColor',
'borderCapStyle',
'borderDash',
'borderDashOffset',
'borderJoinStyle',
'fill'
],
/**
* @private
*/
_dataElementOptions: {
backgroundColor: 'pointBackgroundColor',
borderColor: 'pointBorderColor',
borderWidth: 'pointBorderWidth',
hitRadius: 'pointHitRadius',
hoverBackgroundColor: 'pointHoverBackgroundColor',
hoverBorderColor: 'pointHoverBorderColor',
hoverBorderWidth: 'pointHoverBorderWidth',
hoverRadius: 'pointHoverRadius',
pointStyle: 'pointStyle',
radius: 'pointRadius',
rotation: 'pointRotation'
},
/**
* @private
*/
_getIndexScaleId: function() {
return this.chart.scale.id;
},
/**
* @private
*/
_getValueScaleId: function() {
return this.chart.scale.id;
},
update: function(reset) {
var me = this;
var meta = me.getMeta();
var line = meta.dataset;
var points = meta.data || [];
var scale = me.chart.scale;
var config = me._config;
var i, ilen;
// Compatibility: If the properties are defined with only the old name, use those values
if (config.tension !== undefined && config.lineTension === undefined) {
config.lineTension = config.tension;
}
// Utility
line._scale = scale;
line._datasetIndex = me.index;
// Data
line._children = points;
line._loop = true;
// Model
line._model = me._resolveDatasetElementOptions(line);
line.pivot();
// Update Points
for (i = 0, ilen = points.length; i < ilen; ++i) {
me.updateElement(points[i], i, reset);
}
// Update bezier control points
me.updateBezierControlPoints();
// Now pivot the point for animation
for (i = 0, ilen = points.length; i < ilen; ++i) {
points[i].pivot();
}
},
updateElement: function(point, index, reset) {
var me = this;
var custom = point.custom || {};
var dataset = me.getDataset();
var scale = me.chart.scale;
var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
var options = me._resolveDataElementOptions(point, index);
var lineModel = me.getMeta().dataset._model;
var x = reset ? scale.xCenter : pointPosition.x;
var y = reset ? scale.yCenter : pointPosition.y;
// Utility
point._scale = scale;
point._options = options;
point._datasetIndex = me.index;
point._index = index;
// Desired view properties
point._model = {
x: x, // value not used in dataset scale, but we want a consistent API between scales
y: y,
skip: custom.skip || isNaN(x) || isNaN(y),
// Appearance
radius: options.radius,
pointStyle: options.pointStyle,
rotation: options.rotation,
backgroundColor: options.backgroundColor,
borderColor: options.borderColor,
borderWidth: options.borderWidth,
tension: valueOrDefault(custom.tension, lineModel ? lineModel.tension : 0),
// Tooltip
hitRadius: options.hitRadius
};
},
/**
* @private
*/
_resolveDatasetElementOptions: function() {
var me = this;
var config = me._config;
var options = me.chart.options;
var values = DatasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
values.spanGaps = valueOrDefault(config.spanGaps, options.spanGaps);
values.tension = valueOrDefault(config.lineTension, options.elements.line.tension);
return values;
},
updateBezierControlPoints: function() {
var me = this;
var meta = me.getMeta();
var area = me.chart.chartArea;
var points = meta.data || [];
var i, ilen, model, controlPoints;
// Only consider points that are drawn in case the spanGaps option is used
if (meta.dataset._model.spanGaps) {
points = points.filter(function(pt) {
return !pt._model.skip;
});
}
function capControlPoint(pt, min, max) {
return Math.max(Math.min(pt, max), min);
}
for (i = 0, ilen = points.length; i < ilen; ++i) {
model = points[i]._model;
controlPoints = helpers.splineCurve(
helpers.previousItem(points, i, true)._model,
model,
helpers.nextItem(points, i, true)._model,
model.tension
);
// Prevent the bezier going outside of the bounds of the graph
model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
}
},
setHoverStyle: function(point) {
var model = point._model;
var options = point._options;
var getHoverColor = helpers.getHoverColor;
point.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth,
radius: model.radius
};
model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
model.radius = valueOrDefault(options.hoverRadius, options.radius);
}
});

View File

@@ -0,0 +1,45 @@
'use strict';
var LineController = require('./controller.line');
var defaults = require('../core/core.defaults');
defaults._set('scatter', {
hover: {
mode: 'single'
},
scales: {
xAxes: [{
id: 'x-axis-1', // need an ID so datasets can reference the scale
type: 'linear', // scatter should not use a category axis
position: 'bottom'
}],
yAxes: [{
id: 'y-axis-1',
type: 'linear',
position: 'left'
}]
},
tooltips: {
callbacks: {
title: function() {
return ''; // doesn't make sense for scatter since data are formatted as a point
},
label: function(item) {
return '(' + item.xLabel + ', ' + item.yLabel + ')';
}
}
}
});
defaults._set('global', {
datasets: {
scatter: {
showLine: false
}
}
});
// Scatter charts use line controllers
module.exports = LineController;

View File

@@ -0,0 +1,27 @@
'use strict';
var bar = require('./controller.bar');
var bubble = require('./controller.bubble');
var doughnut = require('./controller.doughnut');
var horizontalBar = require('./controller.horizontalBar');
var line = require('./controller.line');
var polarArea = require('./controller.polarArea');
var pie = require('./controller.pie');
var radar = require('./controller.radar');
var scatter = require('./controller.scatter');
// NOTE export a map in which the key represents the controller type, not
// the class, and so must be CamelCase in order to be correctly retrieved
// by the controller in core.controller.js (`controllers[meta.type]`).
module.exports = {
bar: bar,
bubble: bubble,
doughnut: doughnut,
horizontalBar: horizontalBar,
line: line,
polarArea: polarArea,
pie: pie,
radar: radar,
scatter: scatter
};

View File

@@ -0,0 +1,121 @@
/**
* @namespace Chart._adapters
* @since 2.8.0
* @private
*/
'use strict';
var helpers = require('../helpers/index');
function abstract() {
throw new Error(
'This method is not implemented: either no adapter can ' +
'be found or an incomplete integration was provided.'
);
}
/**
* Date adapter (current used by the time scale)
* @namespace Chart._adapters._date
* @memberof Chart._adapters
* @private
*/
/**
* Currently supported unit string values.
* @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
* @memberof Chart._adapters._date
* @name Unit
*/
/**
* @class
*/
function DateAdapter(options) {
this.options = options || {};
}
helpers.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
/**
* Returns a map of time formats for the supported formatting units defined
* in Unit as well as 'datetime' representing a detailed date/time string.
* @returns {{string: string}}
*/
formats: abstract,
/**
* Parses the given `value` and return the associated timestamp.
* @param {any} value - the value to parse (usually comes from the data)
* @param {string} [format] - the expected data format
* @returns {(number|null)}
* @function
*/
parse: abstract,
/**
* Returns the formatted date in the specified `format` for a given `timestamp`.
* @param {number} timestamp - the timestamp to format
* @param {string} format - the date/time token
* @return {string}
* @function
*/
format: abstract,
/**
* Adds the specified `amount` of `unit` to the given `timestamp`.
* @param {number} timestamp - the input timestamp
* @param {number} amount - the amount to add
* @param {Unit} unit - the unit as string
* @return {number}
* @function
*/
add: abstract,
/**
* Returns the number of `unit` between the given timestamps.
* @param {number} max - the input timestamp (reference)
* @param {number} min - the timestamp to substract
* @param {Unit} unit - the unit as string
* @return {number}
* @function
*/
diff: abstract,
/**
* Returns start of `unit` for the given `timestamp`.
* @param {number} timestamp - the input timestamp
* @param {Unit} unit - the unit as string
* @param {number} [weekday] - the ISO day of the week with 1 being Monday
* and 7 being Sunday (only needed if param *unit* is `isoWeek`).
* @function
*/
startOf: abstract,
/**
* Returns end of `unit` for the given `timestamp`.
* @param {number} timestamp - the input timestamp
* @param {Unit} unit - the unit as string
* @function
*/
endOf: abstract,
// DEPRECATIONS
/**
* Provided for backward compatibility for scale.getValueForPixel(),
* this method should be overridden only by the moment adapter.
* @deprecated since version 2.8.0
* @todo remove at version 3
* @private
*/
_create: function(value) {
return value;
}
});
DateAdapter.override = function(members) {
helpers.extend(DateAdapter.prototype, members);
};
module.exports._date = DateAdapter;

View File

@@ -0,0 +1,45 @@
'use strict';
var Element = require('./core.element');
var exports = Element.extend({
chart: null, // the animation associated chart instance
currentStep: 0, // the current animation step
numSteps: 60, // default number of steps
easing: '', // the easing to use for this animation
render: null, // render function used by the animation service
onAnimationProgress: null, // user specified callback to fire on each step of the animation
onAnimationComplete: null, // user specified callback to fire when the animation finishes
});
module.exports = exports;
// DEPRECATIONS
/**
* Provided for backward compatibility, use Chart.Animation instead
* @prop Chart.Animation#animationObject
* @deprecated since version 2.6.0
* @todo remove at version 3
*/
Object.defineProperty(exports.prototype, 'animationObject', {
get: function() {
return this;
}
});
/**
* Provided for backward compatibility, use Chart.Animation#chart instead
* @prop Chart.Animation#chartInstance
* @deprecated since version 2.6.0
* @todo remove at version 3
*/
Object.defineProperty(exports.prototype, 'chartInstance', {
get: function() {
return this.chart;
},
set: function(value) {
this.chart = value;
}
});

View File

@@ -0,0 +1,122 @@
/* global window: false */
'use strict';
var defaults = require('./core.defaults');
var helpers = require('../helpers/index');
defaults._set('global', {
animation: {
duration: 1000,
easing: 'easeOutQuart',
onProgress: helpers.noop,
onComplete: helpers.noop
}
});
module.exports = {
animations: [],
request: null,
/**
* @param {Chart} chart - The chart to animate.
* @param {Chart.Animation} animation - The animation that we will animate.
* @param {number} duration - The animation duration in ms.
* @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
*/
addAnimation: function(chart, animation, duration, lazy) {
var animations = this.animations;
var i, ilen;
animation.chart = chart;
animation.startTime = Date.now();
animation.duration = duration;
if (!lazy) {
chart.animating = true;
}
for (i = 0, ilen = animations.length; i < ilen; ++i) {
if (animations[i].chart === chart) {
animations[i] = animation;
return;
}
}
animations.push(animation);
// If there are no animations queued, manually kickstart a digest, for lack of a better word
if (animations.length === 1) {
this.requestAnimationFrame();
}
},
cancelAnimation: function(chart) {
var index = helpers.findIndex(this.animations, function(animation) {
return animation.chart === chart;
});
if (index !== -1) {
this.animations.splice(index, 1);
chart.animating = false;
}
},
requestAnimationFrame: function() {
var me = this;
if (me.request === null) {
// Skip animation frame requests until the active one is executed.
// This can happen when processing mouse events, e.g. 'mousemove'
// and 'mouseout' events will trigger multiple renders.
me.request = helpers.requestAnimFrame.call(window, function() {
me.request = null;
me.startDigest();
});
}
},
/**
* @private
*/
startDigest: function() {
var me = this;
me.advance();
// Do we have more stuff to animate?
if (me.animations.length > 0) {
me.requestAnimationFrame();
}
},
/**
* @private
*/
advance: function() {
var animations = this.animations;
var animation, chart, numSteps, nextStep;
var i = 0;
// 1 animation per chart, so we are looping charts here
while (i < animations.length) {
animation = animations[i];
chart = animation.chart;
numSteps = animation.numSteps;
// Make sure that currentStep starts at 1
// https://github.com/chartjs/Chart.js/issues/6104
nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
animation.currentStep = Math.min(nextStep, numSteps);
helpers.callback(animation.render, [chart, animation], chart);
helpers.callback(animation.onAnimationProgress, [animation], chart);
if (animation.currentStep >= numSteps) {
helpers.callback(animation.onAnimationComplete, [animation], chart);
chart.animating = false;
animations.splice(i, 1);
} else {
++i;
}
}
}
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,575 @@
'use strict';
var helpers = require('../helpers/index');
var resolve = helpers.options.resolve;
var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
/**
* Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
* 'unshift') and notify the listener AFTER the array has been altered. Listeners are
* called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
*/
function listenArrayEvents(array, listener) {
if (array._chartjs) {
array._chartjs.listeners.push(listener);
return;
}
Object.defineProperty(array, '_chartjs', {
configurable: true,
enumerable: false,
value: {
listeners: [listener]
}
});
arrayEvents.forEach(function(key) {
var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
var base = array[key];
Object.defineProperty(array, key, {
configurable: true,
enumerable: false,
value: function() {
var args = Array.prototype.slice.call(arguments);
var res = base.apply(this, args);
helpers.each(array._chartjs.listeners, function(object) {
if (typeof object[method] === 'function') {
object[method].apply(object, args);
}
});
return res;
}
});
});
}
/**
* Removes the given array event listener and cleanup extra attached properties (such as
* the _chartjs stub and overridden methods) if array doesn't have any more listeners.
*/
function unlistenArrayEvents(array, listener) {
var stub = array._chartjs;
if (!stub) {
return;
}
var listeners = stub.listeners;
var index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
if (listeners.length > 0) {
return;
}
arrayEvents.forEach(function(key) {
delete array[key];
});
delete array._chartjs;
}
// Base class for all dataset controllers (line, bar, etc)
var DatasetController = function(chart, datasetIndex) {
this.initialize(chart, datasetIndex);
};
helpers.extend(DatasetController.prototype, {
/**
* Element type used to generate a meta dataset (e.g. Chart.element.Line).
* @type {Chart.core.element}
*/
datasetElementType: null,
/**
* Element type used to generate a meta data (e.g. Chart.element.Point).
* @type {Chart.core.element}
*/
dataElementType: null,
/**
* Dataset element option keys to be resolved in _resolveDatasetElementOptions.
* A derived controller may override this to resolve controller-specific options.
* The keys defined here are for backward compatibility for legend styles.
* @private
*/
_datasetElementOptions: [
'backgroundColor',
'borderCapStyle',
'borderColor',
'borderDash',
'borderDashOffset',
'borderJoinStyle',
'borderWidth'
],
/**
* Data element option keys to be resolved in _resolveDataElementOptions.
* A derived controller may override this to resolve controller-specific options.
* The keys defined here are for backward compatibility for legend styles.
* @private
*/
_dataElementOptions: [
'backgroundColor',
'borderColor',
'borderWidth',
'pointStyle'
],
initialize: function(chart, datasetIndex) {
var me = this;
me.chart = chart;
me.index = datasetIndex;
me.linkScales();
me.addElements();
me._type = me.getMeta().type;
},
updateIndex: function(datasetIndex) {
this.index = datasetIndex;
},
linkScales: function() {
var me = this;
var meta = me.getMeta();
var chart = me.chart;
var scales = chart.scales;
var dataset = me.getDataset();
var scalesOpts = chart.options.scales;
if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
}
if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
}
},
getDataset: function() {
return this.chart.data.datasets[this.index];
},
getMeta: function() {
return this.chart.getDatasetMeta(this.index);
},
getScaleForId: function(scaleID) {
return this.chart.scales[scaleID];
},
/**
* @private
*/
_getValueScaleId: function() {
return this.getMeta().yAxisID;
},
/**
* @private
*/
_getIndexScaleId: function() {
return this.getMeta().xAxisID;
},
/**
* @private
*/
_getValueScale: function() {
return this.getScaleForId(this._getValueScaleId());
},
/**
* @private
*/
_getIndexScale: function() {
return this.getScaleForId(this._getIndexScaleId());
},
reset: function() {
this._update(true);
},
/**
* @private
*/
destroy: function() {
if (this._data) {
unlistenArrayEvents(this._data, this);
}
},
createMetaDataset: function() {
var me = this;
var type = me.datasetElementType;
return type && new type({
_chart: me.chart,
_datasetIndex: me.index
});
},
createMetaData: function(index) {
var me = this;
var type = me.dataElementType;
return type && new type({
_chart: me.chart,
_datasetIndex: me.index,
_index: index
});
},
addElements: function() {
var me = this;
var meta = me.getMeta();
var data = me.getDataset().data || [];
var metaData = meta.data;
var i, ilen;
for (i = 0, ilen = data.length; i < ilen; ++i) {
metaData[i] = metaData[i] || me.createMetaData(i);
}
meta.dataset = meta.dataset || me.createMetaDataset();
},
addElementAndReset: function(index) {
var element = this.createMetaData(index);
this.getMeta().data.splice(index, 0, element);
this.updateElement(element, index, true);
},
buildOrUpdateElements: function() {
var me = this;
var dataset = me.getDataset();
var data = dataset.data || (dataset.data = []);
// In order to correctly handle data addition/deletion animation (an thus simulate
// real-time charts), we need to monitor these data modifications and synchronize
// the internal meta data accordingly.
if (me._data !== data) {
if (me._data) {
// This case happens when the user replaced the data array instance.
unlistenArrayEvents(me._data, me);
}
if (data && Object.isExtensible(data)) {
listenArrayEvents(data, me);
}
me._data = data;
}
// Re-sync meta data in case the user replaced the data array or if we missed
// any updates and so make sure that we handle number of datapoints changing.
me.resyncElements();
},
/**
* Returns the merged user-supplied and default dataset-level options
* @private
*/
_configure: function() {
var me = this;
me._config = helpers.merge({}, [
me.chart.options.datasets[me._type],
me.getDataset(),
], {
merger: function(key, target, source) {
if (key !== '_meta' && key !== 'data') {
helpers._merger(key, target, source);
}
}
});
},
_update: function(reset) {
var me = this;
me._configure();
me._cachedDataOpts = null;
me.update(reset);
},
update: helpers.noop,
transition: function(easingValue) {
var meta = this.getMeta();
var elements = meta.data || [];
var ilen = elements.length;
var i = 0;
for (; i < ilen; ++i) {
elements[i].transition(easingValue);
}
if (meta.dataset) {
meta.dataset.transition(easingValue);
}
},
draw: function() {
var meta = this.getMeta();
var elements = meta.data || [];
var ilen = elements.length;
var i = 0;
if (meta.dataset) {
meta.dataset.draw();
}
for (; i < ilen; ++i) {
elements[i].draw();
}
},
/**
* Returns a set of predefined style properties that should be used to represent the dataset
* or the data if the index is specified
* @param {number} index - data index
* @return {IStyleInterface} style object
*/
getStyle: function(index) {
var me = this;
var meta = me.getMeta();
var dataset = meta.dataset;
var style;
me._configure();
if (dataset && index === undefined) {
style = me._resolveDatasetElementOptions(dataset || {});
} else {
index = index || 0;
style = me._resolveDataElementOptions(meta.data[index] || {}, index);
}
if (style.fill === false || style.fill === null) {
style.backgroundColor = style.borderColor;
}
return style;
},
/**
* @private
*/
_resolveDatasetElementOptions: function(element, hover) {
var me = this;
var chart = me.chart;
var datasetOpts = me._config;
var custom = element.custom || {};
var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
var elementOptions = me._datasetElementOptions;
var values = {};
var i, ilen, key, readKey;
// Scriptable options
var context = {
chart: chart,
dataset: me.getDataset(),
datasetIndex: me.index,
hover: hover
};
for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
key = elementOptions[i];
readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
values[key] = resolve([
custom[readKey],
datasetOpts[readKey],
options[readKey]
], context);
}
return values;
},
/**
* @private
*/
_resolveDataElementOptions: function(element, index) {
var me = this;
var custom = element && element.custom;
var cached = me._cachedDataOpts;
if (cached && !custom) {
return cached;
}
var chart = me.chart;
var datasetOpts = me._config;
var options = chart.options.elements[me.dataElementType.prototype._type] || {};
var elementOptions = me._dataElementOptions;
var values = {};
// Scriptable options
var context = {
chart: chart,
dataIndex: index,
dataset: me.getDataset(),
datasetIndex: me.index
};
// `resolve` sets cacheable to `false` if any option is indexed or scripted
var info = {cacheable: !custom};
var keys, i, ilen, key;
custom = custom || {};
if (helpers.isArray(elementOptions)) {
for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
key = elementOptions[i];
values[key] = resolve([
custom[key],
datasetOpts[key],
options[key]
], context, index, info);
}
} else {
keys = Object.keys(elementOptions);
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
values[key] = resolve([
custom[key],
datasetOpts[elementOptions[key]],
datasetOpts[key],
options[key]
], context, index, info);
}
}
if (info.cacheable) {
me._cachedDataOpts = Object.freeze(values);
}
return values;
},
removeHoverStyle: function(element) {
helpers.merge(element._model, element.$previousStyle || {});
delete element.$previousStyle;
},
setHoverStyle: function(element) {
var dataset = this.chart.data.datasets[element._datasetIndex];
var index = element._index;
var custom = element.custom || {};
var model = element._model;
var getHoverColor = helpers.getHoverColor;
element.$previousStyle = {
backgroundColor: model.backgroundColor,
borderColor: model.borderColor,
borderWidth: model.borderWidth
};
model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
},
/**
* @private
*/
_removeDatasetHoverStyle: function() {
var element = this.getMeta().dataset;
if (element) {
this.removeHoverStyle(element);
}
},
/**
* @private
*/
_setDatasetHoverStyle: function() {
var element = this.getMeta().dataset;
var prev = {};
var i, ilen, key, keys, hoverOptions, model;
if (!element) {
return;
}
model = element._model;
hoverOptions = this._resolveDatasetElementOptions(element, true);
keys = Object.keys(hoverOptions);
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
prev[key] = model[key];
model[key] = hoverOptions[key];
}
element.$previousStyle = prev;
},
/**
* @private
*/
resyncElements: function() {
var me = this;
var meta = me.getMeta();
var data = me.getDataset().data;
var numMeta = meta.data.length;
var numData = data.length;
if (numData < numMeta) {
meta.data.splice(numData, numMeta - numData);
} else if (numData > numMeta) {
me.insertElements(numMeta, numData - numMeta);
}
},
/**
* @private
*/
insertElements: function(start, count) {
for (var i = 0; i < count; ++i) {
this.addElementAndReset(start + i);
}
},
/**
* @private
*/
onDataPush: function() {
var count = arguments.length;
this.insertElements(this.getDataset().data.length - count, count);
},
/**
* @private
*/
onDataPop: function() {
this.getMeta().data.pop();
},
/**
* @private
*/
onDataShift: function() {
this.getMeta().data.shift();
},
/**
* @private
*/
onDataSplice: function(start, count) {
this.getMeta().data.splice(start, count);
this.insertElements(start, arguments.length - 2);
},
/**
* @private
*/
onDataUnshift: function() {
this.insertElements(0, arguments.length);
}
});
DatasetController.extend = helpers.inherits;
module.exports = DatasetController;

View File

@@ -0,0 +1,26 @@
'use strict';
var helpers = require('../helpers/helpers.core');
var defaults = {
/**
* @private
*/
_set: function(scope, values) {
return helpers.merge(this[scope] || (this[scope] = {}), values);
}
};
// TODO(v3): remove 'global' from namespace. all default are global and
// there's inconsistency around which options are under 'global'
defaults._set('global', {
defaultColor: 'rgba(0,0,0,0.1)',
defaultFontColor: '#666',
defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
defaultFontSize: 12,
defaultFontStyle: 'normal',
defaultLineHeight: 1.2,
showLines: true
});
module.exports = defaults;

View File

@@ -0,0 +1,116 @@
'use strict';
var color = require('chartjs-color');
var helpers = require('../helpers/index');
function interpolate(start, view, model, ease) {
var keys = Object.keys(model);
var i, ilen, key, actual, origin, target, type, c0, c1;
for (i = 0, ilen = keys.length; i < ilen; ++i) {
key = keys[i];
target = model[key];
// if a value is added to the model after pivot() has been called, the view
// doesn't contain it, so let's initialize the view to the target value.
if (!view.hasOwnProperty(key)) {
view[key] = target;
}
actual = view[key];
if (actual === target || key[0] === '_') {
continue;
}
if (!start.hasOwnProperty(key)) {
start[key] = actual;
}
origin = start[key];
type = typeof target;
if (type === typeof origin) {
if (type === 'string') {
c0 = color(origin);
if (c0.valid) {
c1 = color(target);
if (c1.valid) {
view[key] = c1.mix(c0, ease).rgbString();
continue;
}
}
} else if (helpers.isFinite(origin) && helpers.isFinite(target)) {
view[key] = origin + (target - origin) * ease;
continue;
}
}
view[key] = target;
}
}
var Element = function(configuration) {
helpers.extend(this, configuration);
this.initialize.apply(this, arguments);
};
helpers.extend(Element.prototype, {
_type: undefined,
initialize: function() {
this.hidden = false;
},
pivot: function() {
var me = this;
if (!me._view) {
me._view = helpers.extend({}, me._model);
}
me._start = {};
return me;
},
transition: function(ease) {
var me = this;
var model = me._model;
var start = me._start;
var view = me._view;
// No animation -> No Transition
if (!model || ease === 1) {
me._view = helpers.extend({}, model);
me._start = null;
return me;
}
if (!view) {
view = me._view = {};
}
if (!start) {
start = me._start = {};
}
interpolate(start, view, model, ease);
return me;
},
tooltipPosition: function() {
return {
x: this._model.x,
y: this._model.y
};
},
hasValue: function() {
return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y);
}
});
Element.extend = helpers.inherits;
module.exports = Element;

View File

@@ -0,0 +1,620 @@
/* global window: false */
/* global document: false */
'use strict';
var color = require('chartjs-color');
var defaults = require('./core.defaults');
var helpers = require('../helpers/index');
module.exports = function() {
// -- Basic js utility methods
helpers.where = function(collection, filterCallback) {
if (helpers.isArray(collection) && Array.prototype.filter) {
return collection.filter(filterCallback);
}
var filtered = [];
helpers.each(collection, function(item) {
if (filterCallback(item)) {
filtered.push(item);
}
});
return filtered;
};
helpers.findIndex = Array.prototype.findIndex ?
function(array, callback, scope) {
return array.findIndex(callback, scope);
} :
function(array, callback, scope) {
scope = scope === undefined ? array : scope;
for (var i = 0, ilen = array.length; i < ilen; ++i) {
if (callback.call(scope, array[i], i, array)) {
return i;
}
}
return -1;
};
helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
// Default to start of the array
if (helpers.isNullOrUndef(startIndex)) {
startIndex = -1;
}
for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)) {
return currentItem;
}
}
};
helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
// Default to end of the array
if (helpers.isNullOrUndef(startIndex)) {
startIndex = arrayToSearch.length;
}
for (var i = startIndex - 1; i >= 0; i--) {
var currentItem = arrayToSearch[i];
if (filterCallback(currentItem)) {
return currentItem;
}
}
};
// -- Math methods
helpers.isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
helpers.almostEquals = function(x, y, epsilon) {
return Math.abs(x - y) < epsilon;
};
helpers.almostWhole = function(x, epsilon) {
var rounded = Math.round(x);
return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
};
helpers.max = function(array) {
return array.reduce(function(max, value) {
if (!isNaN(value)) {
return Math.max(max, value);
}
return max;
}, Number.NEGATIVE_INFINITY);
};
helpers.min = function(array) {
return array.reduce(function(min, value) {
if (!isNaN(value)) {
return Math.min(min, value);
}
return min;
}, Number.POSITIVE_INFINITY);
};
helpers.sign = Math.sign ?
function(x) {
return Math.sign(x);
} :
function(x) {
x = +x; // convert to a number
if (x === 0 || isNaN(x)) {
return x;
}
return x > 0 ? 1 : -1;
};
helpers.toRadians = function(degrees) {
return degrees * (Math.PI / 180);
};
helpers.toDegrees = function(radians) {
return radians * (180 / Math.PI);
};
/**
* Returns the number of decimal places
* i.e. the number of digits after the decimal point, of the value of this Number.
* @param {number} x - A number.
* @returns {number} The number of decimal places.
* @private
*/
helpers._decimalPlaces = function(x) {
if (!helpers.isFinite(x)) {
return;
}
var e = 1;
var p = 0;
while (Math.round(x * e) / e !== x) {
e *= 10;
p++;
}
return p;
};
// Gets the angle from vertical upright to the point about a centre.
helpers.getAngleFromPoint = function(centrePoint, anglePoint) {
var distanceFromXCenter = anglePoint.x - centrePoint.x;
var distanceFromYCenter = anglePoint.y - centrePoint.y;
var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
if (angle < (-0.5 * Math.PI)) {
angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
}
return {
angle: angle,
distance: radialDistanceFromCenter
};
};
helpers.distanceBetweenPoints = function(pt1, pt2) {
return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
};
/**
* Provided for backward compatibility, not available anymore
* @function Chart.helpers.aliasPixel
* @deprecated since version 2.8.0
* @todo remove at version 3
*/
helpers.aliasPixel = function(pixelWidth) {
return (pixelWidth % 2 === 0) ? 0 : 0.5;
};
/**
* Returns the aligned pixel value to avoid anti-aliasing blur
* @param {Chart} chart - The chart instance.
* @param {number} pixel - A pixel value.
* @param {number} width - The width of the element.
* @returns {number} The aligned pixel value.
* @private
*/
helpers._alignPixel = function(chart, pixel, width) {
var devicePixelRatio = chart.currentDevicePixelRatio;
var halfWidth = width / 2;
return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
};
helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
// Props to Rob Spencer at scaled innovation for his post on splining between points
// http://scaledinnovation.com/analytics/splines/aboutSplines.html
// This function must also respect "skipped" points
var previous = firstPoint.skip ? middlePoint : firstPoint;
var current = middlePoint;
var next = afterPoint.skip ? middlePoint : afterPoint;
var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
var s01 = d01 / (d01 + d12);
var s12 = d12 / (d01 + d12);
// If all points are the same, s01 & s02 will be inf
s01 = isNaN(s01) ? 0 : s01;
s12 = isNaN(s12) ? 0 : s12;
var fa = t * s01; // scaling factor for triangle Ta
var fb = t * s12;
return {
previous: {
x: current.x - fa * (next.x - previous.x),
y: current.y - fa * (next.y - previous.y)
},
next: {
x: current.x + fb * (next.x - previous.x),
y: current.y + fb * (next.y - previous.y)
}
};
};
helpers.EPSILON = Number.EPSILON || 1e-14;
helpers.splineCurveMonotone = function(points) {
// This function calculates Bézier control points in a similar way than |splineCurve|,
// but preserves monotonicity of the provided data and ensures no local extremums are added
// between the dataset discrete points due to the interpolation.
// See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
var pointsWithTangents = (points || []).map(function(point) {
return {
model: point._model,
deltaK: 0,
mK: 0
};
});
// Calculate slopes (deltaK) and initialize tangents (mK)
var pointsLen = pointsWithTangents.length;
var i, pointBefore, pointCurrent, pointAfter;
for (i = 0; i < pointsLen; ++i) {
pointCurrent = pointsWithTangents[i];
if (pointCurrent.model.skip) {
continue;
}
pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
if (pointAfter && !pointAfter.model.skip) {
var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
// In the case of two points that appear at the same x pixel, slopeDeltaX is 0
pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
}
if (!pointBefore || pointBefore.model.skip) {
pointCurrent.mK = pointCurrent.deltaK;
} else if (!pointAfter || pointAfter.model.skip) {
pointCurrent.mK = pointBefore.deltaK;
} else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
pointCurrent.mK = 0;
} else {
pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
}
}
// Adjust tangents to ensure monotonic properties
var alphaK, betaK, tauK, squaredMagnitude;
for (i = 0; i < pointsLen - 1; ++i) {
pointCurrent = pointsWithTangents[i];
pointAfter = pointsWithTangents[i + 1];
if (pointCurrent.model.skip || pointAfter.model.skip) {
continue;
}
if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
pointCurrent.mK = pointAfter.mK = 0;
continue;
}
alphaK = pointCurrent.mK / pointCurrent.deltaK;
betaK = pointAfter.mK / pointCurrent.deltaK;
squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
if (squaredMagnitude <= 9) {
continue;
}
tauK = 3 / Math.sqrt(squaredMagnitude);
pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
}
// Compute control points
var deltaX;
for (i = 0; i < pointsLen; ++i) {
pointCurrent = pointsWithTangents[i];
if (pointCurrent.model.skip) {
continue;
}
pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
if (pointBefore && !pointBefore.model.skip) {
deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
}
if (pointAfter && !pointAfter.model.skip) {
deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
}
}
};
helpers.nextItem = function(collection, index, loop) {
if (loop) {
return index >= collection.length - 1 ? collection[0] : collection[index + 1];
}
return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
};
helpers.previousItem = function(collection, index, loop) {
if (loop) {
return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
}
return index <= 0 ? collection[0] : collection[index - 1];
};
// Implementation of the nice number algorithm used in determining where axis labels will go
helpers.niceNum = function(range, round) {
var exponent = Math.floor(helpers.log10(range));
var fraction = range / Math.pow(10, exponent);
var niceFraction;
if (round) {
if (fraction < 1.5) {
niceFraction = 1;
} else if (fraction < 3) {
niceFraction = 2;
} else if (fraction < 7) {
niceFraction = 5;
} else {
niceFraction = 10;
}
} else if (fraction <= 1.0) {
niceFraction = 1;
} else if (fraction <= 2) {
niceFraction = 2;
} else if (fraction <= 5) {
niceFraction = 5;
} else {
niceFraction = 10;
}
return niceFraction * Math.pow(10, exponent);
};
// Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
helpers.requestAnimFrame = (function() {
if (typeof window === 'undefined') {
return function(callback) {
callback();
};
}
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
}());
// -- DOM methods
helpers.getRelativePosition = function(evt, chart) {
var mouseX, mouseY;
var e = evt.originalEvent || evt;
var canvas = evt.target || evt.srcElement;
var boundingRect = canvas.getBoundingClientRect();
var touches = e.touches;
if (touches && touches.length > 0) {
mouseX = touches[0].clientX;
mouseY = touches[0].clientY;
} else {
mouseX = e.clientX;
mouseY = e.clientY;
}
// Scale mouse coordinates into canvas coordinates
// by following the pattern laid out by 'jerryj' in the comments of
// https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left'));
var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top'));
var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right'));
var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom'));
var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
// We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
// the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
return {
x: mouseX,
y: mouseY
};
};
// Private helper function to convert max-width/max-height values that may be percentages into a number
function parseMaxStyle(styleValue, node, parentProperty) {
var valueInPixels;
if (typeof styleValue === 'string') {
valueInPixels = parseInt(styleValue, 10);
if (styleValue.indexOf('%') !== -1) {
// percentage * size in dimension
valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
}
} else {
valueInPixels = styleValue;
}
return valueInPixels;
}
/**
* Returns if the given value contains an effective constraint.
* @private
*/
function isConstrainedValue(value) {
return value !== undefined && value !== null && value !== 'none';
}
/**
* Returns the max width or height of the given DOM node in a cross-browser compatible fashion
* @param {HTMLElement} domNode - the node to check the constraint on
* @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
* @param {string} percentageProperty - property of parent to use when calculating width as a percentage
* @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
*/
function getConstraintDimension(domNode, maxStyle, percentageProperty) {
var view = document.defaultView;
var parentNode = helpers._getParentNode(domNode);
var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
var hasCNode = isConstrainedValue(constrainedNode);
var hasCContainer = isConstrainedValue(constrainedContainer);
var infinity = Number.POSITIVE_INFINITY;
if (hasCNode || hasCContainer) {
return Math.min(
hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
}
return 'none';
}
// returns Number or undefined if no constraint
helpers.getConstraintWidth = function(domNode) {
return getConstraintDimension(domNode, 'max-width', 'clientWidth');
};
// returns Number or undefined if no constraint
helpers.getConstraintHeight = function(domNode) {
return getConstraintDimension(domNode, 'max-height', 'clientHeight');
};
/**
* @private
*/
helpers._calculatePadding = function(container, padding, parentDimension) {
padding = helpers.getStyle(container, padding);
return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
};
/**
* @private
*/
helpers._getParentNode = function(domNode) {
var parent = domNode.parentNode;
if (parent && parent.toString() === '[object ShadowRoot]') {
parent = parent.host;
}
return parent;
};
helpers.getMaximumWidth = function(domNode) {
var container = helpers._getParentNode(domNode);
if (!container) {
return domNode.clientWidth;
}
var clientWidth = container.clientWidth;
var paddingLeft = helpers._calculatePadding(container, 'padding-left', clientWidth);
var paddingRight = helpers._calculatePadding(container, 'padding-right', clientWidth);
var w = clientWidth - paddingLeft - paddingRight;
var cw = helpers.getConstraintWidth(domNode);
return isNaN(cw) ? w : Math.min(w, cw);
};
helpers.getMaximumHeight = function(domNode) {
var container = helpers._getParentNode(domNode);
if (!container) {
return domNode.clientHeight;
}
var clientHeight = container.clientHeight;
var paddingTop = helpers._calculatePadding(container, 'padding-top', clientHeight);
var paddingBottom = helpers._calculatePadding(container, 'padding-bottom', clientHeight);
var h = clientHeight - paddingTop - paddingBottom;
var ch = helpers.getConstraintHeight(domNode);
return isNaN(ch) ? h : Math.min(h, ch);
};
helpers.getStyle = function(el, property) {
return el.currentStyle ?
el.currentStyle[property] :
document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
};
helpers.retinaScale = function(chart, forceRatio) {
var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
if (pixelRatio === 1) {
return;
}
var canvas = chart.canvas;
var height = chart.height;
var width = chart.width;
canvas.height = height * pixelRatio;
canvas.width = width * pixelRatio;
chart.ctx.scale(pixelRatio, pixelRatio);
// If no style has been set on the canvas, the render size is used as display size,
// making the chart visually bigger, so let's enforce it to the "correct" values.
// See https://github.com/chartjs/Chart.js/issues/3575
if (!canvas.style.height && !canvas.style.width) {
canvas.style.height = height + 'px';
canvas.style.width = width + 'px';
}
};
// -- Canvas methods
helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
};
helpers.longestText = function(ctx, font, arrayOfThings, cache) {
cache = cache || {};
var data = cache.data = cache.data || {};
var gc = cache.garbageCollect = cache.garbageCollect || [];
if (cache.font !== font) {
data = cache.data = {};
gc = cache.garbageCollect = [];
cache.font = font;
}
ctx.font = font;
var longest = 0;
var ilen = arrayOfThings.length;
var i, j, jlen, thing, nestedThing;
for (i = 0; i < ilen; i++) {
thing = arrayOfThings[i];
// Undefined strings and arrays should not be measured
if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) {
longest = helpers.measureText(ctx, data, gc, longest, thing);
} else if (helpers.isArray(thing)) {
// if it is an array lets measure each element
// to do maybe simplify this function a bit so we can do this more recursively?
for (j = 0, jlen = thing.length; j < jlen; j++) {
nestedThing = thing[j];
// Undefined strings and arrays should not be measured
if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) {
longest = helpers.measureText(ctx, data, gc, longest, nestedThing);
}
}
}
}
var gcLen = gc.length / 2;
if (gcLen > arrayOfThings.length) {
for (i = 0; i < gcLen; i++) {
delete data[gc[i]];
}
gc.splice(0, gcLen);
}
return longest;
};
helpers.measureText = function(ctx, data, gc, longest, string) {
var textWidth = data[string];
if (!textWidth) {
textWidth = data[string] = ctx.measureText(string).width;
gc.push(string);
}
if (textWidth > longest) {
longest = textWidth;
}
return longest;
};
/**
* @deprecated
*/
helpers.numberOfLabelLines = function(arrayOfThings) {
var numberOfLines = 1;
helpers.each(arrayOfThings, function(thing) {
if (helpers.isArray(thing)) {
if (thing.length > numberOfLines) {
numberOfLines = thing.length;
}
}
});
return numberOfLines;
};
helpers.color = !color ?
function(value) {
console.error('Color.js not found!');
return value;
} :
function(value) {
/* global CanvasGradient */
if (value instanceof CanvasGradient) {
value = defaults.global.defaultColor;
}
return color(value);
};
helpers.getHoverColor = function(colorValue) {
/* global CanvasPattern */
return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
colorValue :
helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString();
};
};

View File

@@ -0,0 +1,303 @@
'use strict';
var helpers = require('../helpers/index');
/**
* Helper function to get relative position for an event
* @param {Event|IEvent} event - The event to get the position for
* @param {Chart} chart - The chart
* @returns {object} the event position
*/
function getRelativePosition(e, chart) {
if (e.native) {
return {
x: e.x,
y: e.y
};
}
return helpers.getRelativePosition(e, chart);
}
/**
* Helper function to traverse all of the visible elements in the chart
* @param {Chart} chart - the chart
* @param {function} handler - the callback to execute for each visible item
*/
function parseVisibleItems(chart, handler) {
var metasets = chart._getSortedVisibleDatasetMetas();
var metadata, i, j, ilen, jlen, element;
for (i = 0, ilen = metasets.length; i < ilen; ++i) {
metadata = metasets[i].data;
for (j = 0, jlen = metadata.length; j < jlen; ++j) {
element = metadata[j];
if (!element._view.skip) {
handler(element);
}
}
}
}
/**
* Helper function to get the items that intersect the event position
* @param {ChartElement[]} items - elements to filter
* @param {object} position - the point to be nearest to
* @return {ChartElement[]} the nearest items
*/
function getIntersectItems(chart, position) {
var elements = [];
parseVisibleItems(chart, function(element) {
if (element.inRange(position.x, position.y)) {
elements.push(element);
}
});
return elements;
}
/**
* Helper function to get the items nearest to the event position considering all visible items in teh chart
* @param {Chart} chart - the chart to look at elements from
* @param {object} position - the point to be nearest to
* @param {boolean} intersect - if true, only consider items that intersect the position
* @param {function} distanceMetric - function to provide the distance between points
* @return {ChartElement[]} the nearest items
*/
function getNearestItems(chart, position, intersect, distanceMetric) {
var minDistance = Number.POSITIVE_INFINITY;
var nearestItems = [];
parseVisibleItems(chart, function(element) {
if (intersect && !element.inRange(position.x, position.y)) {
return;
}
var center = element.getCenterPoint();
var distance = distanceMetric(position, center);
if (distance < minDistance) {
nearestItems = [element];
minDistance = distance;
} else if (distance === minDistance) {
// Can have multiple items at the same distance in which case we sort by size
nearestItems.push(element);
}
});
return nearestItems;
}
/**
* Get a distance metric function for two points based on the
* axis mode setting
* @param {string} axis - the axis mode. x|y|xy
*/
function getDistanceMetricForAxis(axis) {
var useX = axis.indexOf('x') !== -1;
var useY = axis.indexOf('y') !== -1;
return function(pt1, pt2) {
var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
};
}
function indexMode(chart, e, options) {
var position = getRelativePosition(e, chart);
// Default axis for index mode is 'x' to match old behaviour
options.axis = options.axis || 'x';
var distanceMetric = getDistanceMetricForAxis(options.axis);
var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
var elements = [];
if (!items.length) {
return [];
}
chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
var element = meta.data[items[0]._index];
// don't count items that are skipped (null data)
if (element && !element._view.skip) {
elements.push(element);
}
});
return elements;
}
/**
* @interface IInteractionOptions
*/
/**
* If true, only consider items that intersect the point
* @name IInterfaceOptions#boolean
* @type Boolean
*/
/**
* Contains interaction related functions
* @namespace Chart.Interaction
*/
module.exports = {
// Helper function for different modes
modes: {
single: function(chart, e) {
var position = getRelativePosition(e, chart);
var elements = [];
parseVisibleItems(chart, function(element) {
if (element.inRange(position.x, position.y)) {
elements.push(element);
return elements;
}
});
return elements.slice(0, 1);
},
/**
* @function Chart.Interaction.modes.label
* @deprecated since version 2.4.0
* @todo remove at version 3
* @private
*/
label: indexMode,
/**
* Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
* If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
* @function Chart.Interaction.modes.index
* @since v2.4.0
* @param {Chart} chart - the chart we are returning items from
* @param {Event} e - the event we are find things at
* @param {IInteractionOptions} options - options to use during interaction
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
index: indexMode,
/**
* Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
* If the options.intersect is false, we find the nearest item and return the items in that dataset
* @function Chart.Interaction.modes.dataset
* @param {Chart} chart - the chart we are returning items from
* @param {Event} e - the event we are find things at
* @param {IInteractionOptions} options - options to use during interaction
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
dataset: function(chart, e, options) {
var position = getRelativePosition(e, chart);
options.axis = options.axis || 'xy';
var distanceMetric = getDistanceMetricForAxis(options.axis);
var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
if (items.length > 0) {
items = chart.getDatasetMeta(items[0]._datasetIndex).data;
}
return items;
},
/**
* @function Chart.Interaction.modes.x-axis
* @deprecated since version 2.4.0. Use index mode and intersect == true
* @todo remove at version 3
* @private
*/
'x-axis': function(chart, e) {
return indexMode(chart, e, {intersect: false});
},
/**
* Point mode returns all elements that hit test based on the event position
* of the event
* @function Chart.Interaction.modes.intersect
* @param {Chart} chart - the chart we are returning items from
* @param {Event} e - the event we are find things at
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
point: function(chart, e) {
var position = getRelativePosition(e, chart);
return getIntersectItems(chart, position);
},
/**
* nearest mode returns the element closest to the point
* @function Chart.Interaction.modes.intersect
* @param {Chart} chart - the chart we are returning items from
* @param {Event} e - the event we are find things at
* @param {IInteractionOptions} options - options to use
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
nearest: function(chart, e, options) {
var position = getRelativePosition(e, chart);
options.axis = options.axis || 'xy';
var distanceMetric = getDistanceMetricForAxis(options.axis);
return getNearestItems(chart, position, options.intersect, distanceMetric);
},
/**
* x mode returns the elements that hit-test at the current x coordinate
* @function Chart.Interaction.modes.x
* @param {Chart} chart - the chart we are returning items from
* @param {Event} e - the event we are find things at
* @param {IInteractionOptions} options - options to use
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
x: function(chart, e, options) {
var position = getRelativePosition(e, chart);
var items = [];
var intersectsItem = false;
parseVisibleItems(chart, function(element) {
if (element.inXRange(position.x)) {
items.push(element);
}
if (element.inRange(position.x, position.y)) {
intersectsItem = true;
}
});
// If we want to trigger on an intersect and we don't have any items
// that intersect the position, return nothing
if (options.intersect && !intersectsItem) {
items = [];
}
return items;
},
/**
* y mode returns the elements that hit-test at the current y coordinate
* @function Chart.Interaction.modes.y
* @param {Chart} chart - the chart we are returning items from
* @param {Event} e - the event we are find things at
* @param {IInteractionOptions} options - options to use
* @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
*/
y: function(chart, e, options) {
var position = getRelativePosition(e, chart);
var items = [];
var intersectsItem = false;
parseVisibleItems(chart, function(element) {
if (element.inYRange(position.y)) {
items.push(element);
}
if (element.inRange(position.x, position.y)) {
intersectsItem = true;
}
});
// If we want to trigger on an intersect and we don't have any items
// that intersect the position, return nothing
if (options.intersect && !intersectsItem) {
items = [];
}
return items;
}
}
};

Some files were not shown because too many files have changed in this diff Show More