Actualización

This commit is contained in:
Xes
2025-04-10 11:37:29 +02:00
parent 4bfeadb360
commit 8969cc929d
39112 changed files with 975884 additions and 0 deletions

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.