Clarifying to answer the question asked in https://github.com/chartjs/Chart.js/issues/6598#issuecomment-613879766
16 KiB
Chart.js 3.x Migration Guide
Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released in April 2016. In the years since then, as Chart.js has grown in popularity and feature set, we've learned some lessons about how to better create a charting library. In order to improve performance, offer new features, and improve maintainability, it was necessary to break backwards compatibility, but we aimed to do so only when worth the benefit. Some major highlights of v3 include:
- Large performance improvements including the ability to skip data parsing and render charts in parallel via webworkers
- Additional configurability and scriptable options with better defaults
- Completely rewritten animation system
- Rewritten filler plugin with numerous bug fixes
- API Documentation generated and verified by TypeDoc
- No more CSS injection
- Tons of bug fixes
End user migration
Setup and installation
- Chart.js is no longer providing the
Chart.bundle.jsandChart.bundle.min.js. Please see the installation and integration docs for details on the recommended way to setup Chart.js if you were using these builds. momentis no longer specified as an npm dependency. If you are using the time scale, you must include one of the available adapters and corresponding date library. You no longer need to exclude moment from your build.
Options
A number of changes were made to the configuration options passed to the Chart constructor. Those changes are documented below.
hover.animationDurationis now configured inanimation.active.durationresponsiveAnimationDurationis now configured inanimation.resize.duration- Polar area
startAngleoption is now consistent withRadar, 0 is at top and value is in degrees. Default is changed from-½πto0. scales.[x/y]Axesarrays were removed. Scales are now configured directly tooptions.scalesobject with the object key being the scale Id.scales.[x/y]Axes.barPercentagewas moved to dataset optionbarPercentagescales.[x/y]Axes.barThicknesswas moved to dataset optionbarThicknessscales.[x/y]Axes.categoryPercentagewas moved to dataset optioncategoryPercentagescales.[x/y]Axes.maxBarThicknesswas moved to dataset optionmaxBarThicknessscales.[x/y]Axes.minBarLengthwas moved to dataset optionminBarLengthscales.[x/y]Axes.ticks.beginAtZerowas renamed toscales[id].beginAtZeroscales.[x/y]Axes.ticks.maxwas renamed toscales[id].maxscales.[x/y]Axes.ticks.minwas renamed toscales[id].minscales.[x/y]Axes.ticks.reversewas renamed toscales[id].reversescales.[x/y]Axes.ticks.suggestedMaxwas renamed toscales[id].suggestedMaxscales.[x/y]Axes.ticks.suggestedMinwas renamed toscales[id].suggestedMinscales.[x/y]Axes.ticks.unitStepSizewas removed. Usescales[id].ticks.stepSizescales.[x/y]Axes.ticks.userCallbackwas renamed toscales[id].ticks.callbackscales.[x/y]Axes.time.formatwas renamed toscales[id].time.parserscales.[x/y]Axes.time.maxwas renamed toscales[id].maxscales.[x/y]Axes.time.minwas renamed toscales[id].minscales.[x/y]Axes.zeroLine*options of axes were removed. Use scriptable scale options instead.- The dataset option
steppedLinewas removed. Usestepped - The dataset option
tensionwas removed. UselineTension - Dataset options are now configured as
options[type].datasetsrather thanoptions.datasets[type] - To override the platform class used in a chart instance, pass
platform: PlatformClassin the config object. Note that the class should be passed, not an instance of the class.
Defaults
globalnamespace was removed fromdefaults. SoChart.defaults.globalis nowChart.defaultsdefaultprefix was removed from defaults. For exampleChart.defaults.global.defaultColoris nowChart.defaults.colordefaultColorwas renamed tocolordefaultFontColorwas renamed tofontColordefaultFontFamilywas renamed tofontFamilydefaultFontSizewas renamed tofontSizedefaultFontStylewas renamed tofontStyledefaultLineHeightwas renamed tolineHeight
Scales
The configuration options for scales is the largest change in v3. The xAxes and yAxes arrays were removed and axis options are individual scales now keyed by scale ID.
The v2 configuration below is shown with it's new v3 configuration
options: {
scales: {
xAxes: [{
id: 'x',
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
enabled: true
},
fontStyle: function(context) {
return context.tick && context.tick.major ? 'bold' : undefined;
},
fontColor: function(context) {
return context.tick && context.tick.major ? '#FF0000' : undefined;
}
}
}],
yAxes: [{
id: 'y',
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
}]
}
}
And now, in v3:
options: {
scales: {
x: {
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
enabled: true
},
fontStyle: function(context) {
return context.tick && context.tick.major ? 'bold' : undefined;
},
fontColor: function(context) {
return context.tick && context.tick.major ? '#FF0000' : undefined;
}
}
},
y: {
display: true,
scaleLabel: {
display: true,
labelString: 'value'
}
}
}
}
Animations
Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see animations docs for details.
Customizability
customattribute of elements was removed. Please use scriptable options- The
hoverproperty of scriptable optionscontextobject was renamed toactiveto align it with the datalabels plugin.
Interactions
interactionsare now limited to the chart area{mode: 'label'}was replaced with{mode: 'index'}{mode: 'single'}was replaced with{mode: 'nearest', intersect: true}modes['X-axis']was replaced with{mode: 'index', intersect: false}options.onClickis now limited to the chart area
Ticks
options.ticks.majorandoptions.ticks.minorwere replaced with scriptable options for tick fonts.Chart.Ticks.formatters.linearwas renamed toChart.Ticks.formatters.numeric.
Tooltip
xLabelandyLabelwere removed. Please useindexandvalue
Developer migration
Removed
The following properties and methods were removed:
Chart
Chart.borderWidthChart.chart.chartChart.ControllerChart.innerRadiusnow lives on doughnut, pie, and polarArea controllersChart.offsetXChart.offsetYChart.outerRadiusnow lives on doughnut, pie, and polarArea controllersChart.prototype.generateLegendChart.platform. It only containeddisableCSSInjection. CSS is never injected in v3.Chart.radiusLengthChart.typesChart.Tooltipis now provided by the tooltip plugin. The positioners can be accessed fromtooltipPlugin.positionersILayoutItem.minSize
Dataset Controller
DatasetController.addElementAndResetDatasetController.createMetaDataDatasetController.createMetaDataset
Elements
Element.getAreaElement.heightElement.hiddenwas replaced by chart level status, usable withgetDataVisibility(index)/toggleDataVisibility(index)Element.initializeElement.inLabelRangeLine.calculatePointY
Helpers
helpers.addEventhelpers.aliasPixelhelpers.configMergehelpers.findIndexhelpers.findNextWherehelpers.findPreviousWherehelpers.extend. UseObject.assigninsteadhelpers.indexOfhelpers.lineTohelpers.longestTextwas moved to thehelpers.canvasnamespace and made privatehelpers.maxhelpers.measureTextwas moved to thehelpers.canvasnamespace and made privatehelpers.minhelpers.nextItemhelpers.niceNumhelpers.numberOfLabelLineshelpers.previousItemhelpers.removeEventhelpers.roundedRecthelpers.scaleMergehelpers.where
Layout
Layout.defaults
Scales
LogarithmicScale.minNotZeroScale.getRightValueScale.longestLabelWidthScale.longestTextCacheis now privateScale.marginsis now privateScale.mergeTicksOptionsScale.ticksAsNumbersScale.tickValuesis now privateTimeScale.getLabelCapacityis now privateTimeScale.tickFormatFunctionis now private
Plugins (Legend, Title, and Tooltip)
IPlugin.afterScaleUpdate. UseafterLayoutinsteadLegend.marginsis now privateTitle.marginsis now private- The tooltip item's
xandyattributes were removed. UsedatasetIndexandindexto get the element and any corresponding data from it
Removal of private APIs
The following private APIs were removed.
Chart.data.datasets[datasetIndex]._metaElement._ctxElement._modelElement._viewLogarithmicScale._valueOffsetTimeScale.getPixelForOffsetTimeScale.getLabelWidthTooltip._lastActive
Renamed
The following properties were renamed during v3 development:
Chart.Animation.animationObjectwas renamed toChart.AnimationChart.Animation.chartInstancewas renamed toChart.Animation.charthelpers._decimalPlaceswas renamed tohelpers.math._decimalPlaceshelpers.almostEqualswas renamed tohelpers.math.almostEqualshelpers.almostWholewas renamed tohelpers.math.almostWholehelpers.callCallbackwas renamed tohelpers.callbackhelpers.clearwas renamed tohelpers.canvas.clearhelpers.distanceBetweenPointswas renamed tohelpers.math.distanceBetweenPointshelpers.drawRoundedRectanglewas renamed tohelpers.canvas.roundedRecthelpers.getAngleFromPointwas renamed tohelpers.math.getAngleFromPointhelpers.getMaximumHeightwas renamed tohelpers.dom.getMaximumHeighthelpers.getMaximumWidthwas renamed tohelpers.dom.getMaximumWidthhelpers.getRelativePositionwas renamed tohelpers.dom.getRelativePositionhelpers.getStylewas renamed tohelpers.dom.getStylehelpers.getValueAtIndexOrDefaultwas renamed tohelpers.valueAtIndexOrDefaulthelpers.getValueOrDefaultwas renamed tohelpers.valueOrDefaulthelpers.easingEffectswas renamed tohelpers.easing.effectshelpers.log10was renamed tohelpers.math.log10helpers.isNumberwas renamed tohelpers.math.isNumberhelpers.signwas renamed tohelpers.math.signhelpers.retinaScalewas renamed tohelpers.dom.retinaScalehelpers.splineCurvewas renamed tohelpers.curve.splineCurvehelpers.splineCurveMonotonewas renamed tohelpers.curve.splineCurveMonotonehelpers.toDegreeswas renamed tohelpers.math.toDegreeshelpers.toRadianswas renamed tohelpers.math.toRadiansScale.calculateTickRotationwas renamed toScale.calculateLabelRotationTooltip.options.legendColorBackgroupdwas renamed toTooltip.options.multiKeyBackground
Renamed private APIs
The private APIs listed below were renamed:
BarController.calculateBarIndexPixelswas renamed toBarController._calculateBarIndexPixelsBarController.calculateBarValuePixelswas renamed toBarController._calculateBarValuePixelsBarController.getStackCountwas renamed toBarController._getStackCountBarController.getStackIndexwas renamed toBarController._getStackIndexBarController.getRulerwas renamed toBarController._getRulerChart.destroyDatasetMetawas renamed toChart._destroyDatasetMetaChart.drawDatasetwas renamed toChart._drawDatasetChart.drawDatasetswas renamed toChart._drawDatasetsChart.eventHandlerwas renamed toChart._eventHandlerChart.handleEventwas renamed toChart._handleEventChart.initializewas renamed toChart._initializeChart.resetElementswas renamed toChart._resetElementsChart.unbindEventswas renamed toChart._unbindEventsChart.updateDatasetwas renamed toChart._updateDatasetChart.updateDatasetswas renamed toChart._updateDatasetsChart.updateLayoutwas renamed toChart._updateLayoutDatasetController.destroywas renamed toDatasetController._destroyDatasetController.insertElementswas renamed toDatasetController._insertElementsDatasetController.onDataPopwas renamed toDatasetController._onDataPopDatasetController.onDataPushwas renamed toDatasetController._onDataPushDatasetController.onDataShiftwas renamed toDatasetController._onDataShiftDatasetController.onDataSplicewas renamed toDatasetController._onDataSpliceDatasetController.onDataUnshiftwas renamed toDatasetController._onDataUnshiftDatasetController.removeElementswas renamed toDatasetController._removeElementsDatasetController.resyncElementswas renamed toDatasetController._resyncElementsRadialLinearScale.setReductionswas renamed toRadialLinearScale._setReductionsScale.handleMarginswas renamed toScale._handleMarginshelpers._alignPixelwas renamed tohelpers.canvas._alignPixelhelpers._decimalPlaceswas renamed tohelpers.math._decimalPlaces
Changed
The APIs listed in this section have changed in signature or behaviour from version 2.
Scales
Scale.getLabelForIndexwas replaced byscale.getLabelForValueScale.getPixelForValuenow has only one parameter. For theTimeScalethat parameter must be millis since the epochScaleService.registerScaleTypewas renamed toScaleService.registerScaleand now takes a scale constructors which is expected to haveidanddefaultsproperties.
Ticks
Scale.afterBuildTicksnow has no parameters like the other callbacksScale.buildTicksis now expected to return tick objectsScale.convertTicksToLabelswas renamed togenerateTickLabels. It is now expected to set the label property on the ticks given as inputScale.ticksnow contains objects instead of strings- When the
autoSkipoption is enabled,Scale.ticksnow contains only the non-skipped ticks instead of all ticks.
Time Scale
getValueForPixelnow returns milliseconds since the epoch
Controllers
Core Controller
- The first parameter to
updateHoverStyleis now an array of objects containing theelement,datasetIndex, andindex
Dataset Controllers
updateElementwas replaced withupdateElementsnow taking the elements to update, thestartindex, andmodesetHoverStyleandremoveHoverStylenow additionally take thedatasetIndexandindex
Interactions
- Interaction mode methods now return an array of objects containing the
element,datasetIndex, andindex
Layout
ILayoutItem.updateno longer has a return value
Helpers
Canvas Helper
- The second parameter to
drawPointis now the full options object, sostyle,rotation, andradiusare no longer passed explicitly
Platform
Chart.platformis no longer the platform object used by charts. Every chart instance now has a separate platform instance.Chart.platformsis an object that contains two usable platform classes,BasicPlatformandDomPlatform. It also containsBasePlatform, a class that all platforms must extend from.- If the canvas passed in is an instance of
OffscreenCanvas, theBasicPlatformis automatically used.