# 3.x 迁移指南
¥3.x Migration Guide
Chart.js 3.0 引入了许多重大更改。Chart.js 2.0 于 2016 年 4 月发布。从那以后的几年里,随着 Chart.js 的流行和功能集的增长,我们学到了一些关于如何更好地创建图表库的经验教训。为了提高性能、提供新功能和提高可维护性,有必要打破向后兼容性,但我们的目标是只有在值得的时候才这样做。v3 的一些主要亮点包括:
¥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:
大型 performance 改进包括跳过数据解析和通过 webworker 并行渲染图表的能力
¥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
文档从 GitBook 迁移到 Vuepress
¥Documentation migrated from GitBook to Vuepress
由 TypeDoc 生成和验证的 API 文档
¥API documentation generated and verified by TypeDoc
不再有 CSS 注入
¥No more CSS injection
大量错误修复
¥Tons of bug fixes
摇树优化
¥Tree shaking
# 终端用户迁移
¥End user migration
# 设置和安装
¥Setup and installation
分发的文件现在是小写的。例如:
dist/chart.js。¥Distributed files are now in lower case. For example:
dist/chart.js.Chart.js 不再提供
Chart.bundle.js和Chart.bundle.min.js。如果你正在使用这些构建,请参阅 installation 和 integration 文档以了解有关设置 Chart.js 的推荐方法的详细信息。¥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.moment不再指定为 npm 依赖。如果你使用的是time或timeseries秤,则必须包括 可用的适配器 (opens new window) 之一和相应的数据库。你不再需要从构建中排除时刻。¥
momentis no longer specified as an npm dependency. If you are using thetimeortimeseriesscales, you must include one of the available adapters (opens new window) and corresponding date library. You no longer need to exclude moment from your build.如果提供的画布/上下文已在使用中,则
Chart构造函数将抛出错误¥The
Chartconstructor will throw an error if the canvas/context provided is already in useChart.js 3 是 tree-shakeable 的。因此,如果你将它用作项目中的
npm模块并希望使用此功能,则需要导入并注册你要使用的控制器、元素、比例和插件,以获得所有可用项目的列表 导入见 integration。如果通过script标记或从auto注册路径导入 Chart.js 作为npm模块,则不必调用register,在这种情况下,你将无法获得 tree shaking 的好处。下面是一个注册组件的例子:¥Chart.js 3 is tree-shakeable. So if you are using it as an
npmmodule in a project and want to make use of this feature, you need to import and register the controllers, elements, scales and plugins you want to use, for a list of all the available items to import see integration. You will not have to callregisterif importing Chart.js via ascripttag or from theautoregister path as annpmmodule, in this case you will not get the tree shaking benefits. Here is an example of registering components:
import { Chart, LineController, LineElement, PointElement, LinearScale, Title } from `chart.js`
Chart.register(LineController, LineElement, PointElement, LinearScale, Title);
const chart = new Chart(ctx, {
type: 'line',
// data: ...
options: {
plugins: {
title: {
display: true,
text: 'Chart Title'
}
},
scales: {
x: {
type: 'linear'
},
y: {
type: 'linear'
}
}
}
})
# 图表类型
¥Chart types
horizontalBar图表类型已删除。可以使用新的indexAxis选项配置水平柱状图¥
horizontalBarchart type was removed. Horizontal bar charts can be configured using the newindexAxisoption
# 选项
¥Options
对传递给 Chart 构造函数的配置选项进行了一些更改。这些更改记录在下面。
¥A number of changes were made to the configuration options passed to the Chart constructor. Those changes are documented below.
# 一般变化
¥Generic changes
可索引选项现在正在循环。如果有超过 2 个数据点,
backgroundColor: ['red', 'green']将导致'red'/'green'交替出现。¥Indexable options are now looping.
backgroundColor: ['red', 'green']will result in alternating'red'/'green'if there are more than 2 data points.现在可以自由指定对象数据的输入属性,详见 数据结构。
¥The input properties of object data can now be freely specified, see data structures for details.
大多数选项都是使用代理解决的,而不是与默认值合并。除了为不同的上下文轻松启用不同的解析路由之外,它还允许在可编写脚本的选项中使用其他已解析的选项。
¥Most options are resolved utilizing proxies, instead of merging with defaults. In addition to easily enabling different resolution routes for different contexts, it allows using other resolved options in scriptable options.
默认情况下,选项是可编写脚本和可索引的,除非出于某种原因被禁用。
¥Options are by default scriptable and indexable, unless disabled for some reason.
脚本选项接收一个选项解析器作为第二个参数,用于访问同一上下文中的其他选项。
¥Scriptable options receive a option resolver as second parameter for accessing other options in same context.
如果之前没有找到匹配项,则解析会落到上层范围。详见 options。
¥Resolution falls to upper scopes, if no match is found earlier. See options for details.
# 具体变化
¥Specific changes
elements.rectangle现在是elements.bar¥
elements.rectangleis nowelements.barhover.animationDuration现在配置在animation.active.duration¥
hover.animationDurationis now configured inanimation.active.durationresponsiveAnimationDuration现在配置在animation.resize.duration¥
responsiveAnimationDurationis now configured inanimation.resize.duration极地
elements.arc.angle现在以度而不是弧度配置。¥Polar area
elements.arc.angleis now configured in degrees instead of radians.极地
startAngle选项现在与Radar一致,0 在顶部,值以度为单位。默认值从-½π更改为0。¥Polar area
startAngleoption is now consistent withRadar, 0 is at top and value is in degrees. Default is changed from-½πto0.Donut
rotation选项现在以度为单位,0 位于顶部。默认值从-½π更改为0。¥Doughnut
rotationoption is now in degrees and 0 is at top. Default is changed from-½πto0.Donut
circumference选项现在以度为单位。默认值从2π更改为360。¥Doughnut
circumferenceoption is now in degrees. Default is changed from2πto360.Donut
cutoutPercentage已重命名为cutout,并接受像素作为数字和百分比作为以%结尾的字符串。¥Doughnut
cutoutPercentagewas renamed tocutoutand accepts pixels as number and percent as string ending with%.scale选项已被删除,取而代之的是options.scales.r(或任何其他秤 ID,带有axis: 'r')¥
scaleoption was removed in favor ofoptions.scales.r(or any other scale id, withaxis: 'r')scales.[x/y]Axes数组已删除。缩放现在直接配置为options.scales对象,对象键为缩放 ID。¥
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.barPercentage已移至数据集选项barPercentage¥
scales.[x/y]Axes.barPercentagewas moved to dataset optionbarPercentagescales.[x/y]Axes.barThickness已移至数据集选项barThickness¥
scales.[x/y]Axes.barThicknesswas moved to dataset optionbarThicknessscales.[x/y]Axes.categoryPercentage已移至数据集选项categoryPercentage¥
scales.[x/y]Axes.categoryPercentagewas moved to dataset optioncategoryPercentagescales.[x/y]Axes.maxBarThickness已移至数据集选项maxBarThickness¥
scales.[x/y]Axes.maxBarThicknesswas moved to dataset optionmaxBarThicknessscales.[x/y]Axes.minBarLength已移至数据集选项minBarLength¥
scales.[x/y]Axes.minBarLengthwas moved to dataset optionminBarLengthscales.[x/y]Axes.scaleLabel更名为scales[id].title¥
scales.[x/y]Axes.scaleLabelwas renamed toscales[id].titlescales.[x/y]Axes.scaleLabel.labelString更名为scales[id].title.text¥
scales.[x/y]Axes.scaleLabel.labelStringwas renamed toscales[id].title.textscales.[x/y]Axes.ticks.beginAtZero更名为scales[id].beginAtZero¥
scales.[x/y]Axes.ticks.beginAtZerowas renamed toscales[id].beginAtZeroscales.[x/y]Axes.ticks.max更名为scales[id].max¥
scales.[x/y]Axes.ticks.maxwas renamed toscales[id].maxscales.[x/y]Axes.ticks.min更名为scales[id].min¥
scales.[x/y]Axes.ticks.minwas renamed toscales[id].minscales.[x/y]Axes.ticks.reverse更名为scales[id].reverse¥
scales.[x/y]Axes.ticks.reversewas renamed toscales[id].reversescales.[x/y]Axes.ticks.suggestedMax更名为scales[id].suggestedMax¥
scales.[x/y]Axes.ticks.suggestedMaxwas renamed toscales[id].suggestedMaxscales.[x/y]Axes.ticks.suggestedMin更名为scales[id].suggestedMin¥
scales.[x/y]Axes.ticks.suggestedMinwas renamed toscales[id].suggestedMinscales.[x/y]Axes.ticks.unitStepSize已删除。使用scales[id].ticks.stepSize¥
scales.[x/y]Axes.ticks.unitStepSizewas removed. Usescales[id].ticks.stepSizescales.[x/y]Axes.ticks.userCallback更名为scales[id].ticks.callback¥
scales.[x/y]Axes.ticks.userCallbackwas renamed toscales[id].ticks.callbackscales.[x/y]Axes.time.format更名为scales[id].time.parser¥
scales.[x/y]Axes.time.formatwas renamed toscales[id].time.parserscales.[x/y]Axes.time.max更名为scales[id].max¥
scales.[x/y]Axes.time.maxwas renamed toscales[id].maxscales.[x/y]Axes.time.min更名为scales[id].min¥
scales.[x/y]Axes.time.minwas renamed toscales[id].min删除了轴的
scales.[x/y]Axes.zeroLine*选项。请改用可编写脚本的比例选项。¥
scales.[x/y]Axes.zeroLine*options of axes were removed. Use scriptable scale options instead.删除了数据集选项
steppedLine。使用stepped¥The dataset option
steppedLinewas removed. Usestepped图表选项
showLines已重命名为showLine以匹配数据集选项。¥The chart option
showLineswas renamed toshowLineto match the dataset option.图表选项
startAngle已移至radial比例选项。¥The chart option
startAnglewas moved toradialscale options.要覆盖图表实例中使用的平台类,请在配置对象中传递
platform: PlatformClass。请注意,应该传递类,而不是类的实例。¥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.对于圆环图、饼图、极地区域图和雷达图,
aspectRatio默认为 1¥
aspectRatiodefaults to 1 for doughnut, pie, polarArea, and radar charts默认情况下,
TimeScale不再从对象数据中读取t。默认属性为x或y,具体取决于方向。有关如何更改默认值的详细信息,请参阅 数据结构。¥
TimeScaledoes not readtfrom object data by default anymore. The default property isxory, depending on the orientation. See data structures for details on how to change the default.tooltips命名空间已重命名为tooltip以匹配插件名称¥
tooltipsnamespace was renamed totooltipto match the plugin namelegend、title和tooltip名称空间已从options移至options.plugins。¥
legend,titleandtooltipnamespaces were moved fromoptionstooptions.plugins.tooltips.custom更名为plugins.tooltip.external¥
tooltips.customwas renamed toplugins.tooltip.external
# 默认值
¥Defaults
global命名空间已从defaults中删除。所以Chart.defaults.global现在是Chart.defaults¥
globalnamespace was removed fromdefaults. SoChart.defaults.globalis nowChart.defaults数据集控制器默认值已重新定位到
overrides。例如Chart.defaults.line现在是Chart.overrides.line¥Dataset controller defaults were relocate to
overrides. For exampleChart.defaults.lineis nowChart.overrides.linedefault前缀已从默认值中删除。例如Chart.defaults.global.defaultColor现在是Chart.defaults.color¥
defaultprefix was removed from defaults. For exampleChart.defaults.global.defaultColoris nowChart.defaults.colordefaultColor拆分为color、borderColor和backgroundColor¥
defaultColorwas split tocolor,borderColorandbackgroundColordefaultFontColor更名为color¥
defaultFontColorwas renamed tocolordefaultFontFamily更名为font.family¥
defaultFontFamilywas renamed tofont.familydefaultFontSize更名为font.size¥
defaultFontSizewas renamed tofont.sizedefaultFontStyle更名为font.style¥
defaultFontStylewas renamed tofont.styledefaultLineHeight更名为font.lineHeight¥
defaultLineHeightwas renamed tofont.lineHeight水平条默认工具提示模式已从
'index'更改为'nearest'以匹配垂直柱状图¥Horizontal Bar default tooltip mode was changed from
'index'to'nearest'to match vertical bar chartslegend、title和tooltip名称空间已从Chart.defaults移至Chart.defaults.plugins。¥
legend,titleandtooltipnamespaces were moved fromChart.defaultstoChart.defaults.plugins.elements.line.fill默认值从true更改为false。¥
elements.line.filldefault changed fromtruetofalse.折线图不再覆盖默认的
interaction模式。默认值从'index'更改为'nearest'。¥Line charts no longer override the default
interactionmode. Default is changed from'index'to'nearest'.
# 标尺
¥Scales
比例尺的配置选项是 v3 中最大的变化。xAxes 和 yAxes 数组被删除,轴选项是现在由刻度 ID 键控的单独刻度。
¥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.
下面的 v2 配置显示了它的新 v3 配置
¥The v2 configuration below is shown with it's new v3 configuration
options: {
scales: {
xAxes: [{
id: 'x',
type: 'time',
display: true,
title: {
display: true,
text: 'Date'
},
ticks: {
major: {
enabled: true
},
font: function(context) {
if (context.tick && context.tick.major) {
return {
weight: 'bold',
color: '#FF0000'
};
}
}
}
}],
yAxes: [{
id: 'y',
display: true,
title: {
display: true,
text: 'value'
}
}]
}
}
现在,在 v3 中:
¥And now, in v3:
options: {
scales: {
x: {
type: 'time',
display: true,
title: {
display: true,
text: 'Date'
},
ticks: {
major: {
enabled: true
},
color: (context) => context.tick && context.tick.major && '#FF0000',
font: function(context) {
if (context.tick && context.tick.major) {
return {
weight: 'bold'
};
}
}
}
},
y: {
display: true,
title: {
display: true,
text: 'value'
}
}
}
}
删除了时间刻度选项
distribution: 'series',取而代之的是引入了新的刻度类型timeseries¥The time scale option
distribution: 'series'was removed and a new scale typetimeserieswas introduced in its place在时间尺度中,
autoSkip现在默认启用,以与其他尺度保持一致¥In the time scale,
autoSkipis now enabled by default for consistency with the other scales
# 动画
¥Animations
动画系统在 Chart.js v3 中完全重写。每个属性现在都可以单独设置动画。有关详细信息,请参阅 animations 文档。
¥Animation system was completely rewritten in Chart.js v3. Each property can now be animated separately. Please see animations docs for details.
# 可定制性
¥Customizability
删除了元素的
custom属性。请使用可编写脚本的选项¥
customattribute of elements was removed. Please use scriptable options可编写脚本的选项
context对象的hover属性已重命名为active,以使其与数据标签插件保持一致。¥The
hoverproperty of scriptable optionscontextobject was renamed toactiveto align it with the datalabels plugin.
# 交互
¥Interactions
为了允许 DRY 配置,添加了通用交互选项的根选项范围。
options.hover和options.plugins.tooltip现在都从options.interaction继承而来。默认值在defaults.interaction级别定义,因此默认情况下悬停和工具提示交互共享相同的模式等。¥To allow DRY configuration, a root options scope for common interaction options was added.
options.hoverandoptions.plugins.tooltipnow both extend fromoptions.interaction. Defaults are defined atdefaults.interactionlevel, so by default hover and tooltip interactions share the same mode etc.interactions现在仅限于图表区域 + 允许溢出¥
interactionsare now limited to the chart area + allowed overflow{mode: 'label'}已替换为{mode: 'index'}¥
{mode: 'label'}was replaced with{mode: 'index'}{mode: 'single'}已替换为{mode: 'nearest', intersect: true}¥
{mode: 'single'}was replaced with{mode: 'nearest', intersect: true}modes['X-axis']已替换为{mode: 'index', intersect: false}¥
modes['X-axis']was replaced with{mode: 'index', intersect: false}options.onClick现在仅限于图表区域¥
options.onClickis now limited to the chart areaoptions.onClick和options.onHover现在接收chart实例作为第三个参数¥
options.onClickandoptions.onHovernow receive thechartinstance as a 3rd argumentoptions.onHover现在接收一个封装的event作为第一个参数。先前的第一个参数值可通过event.native访问。¥
options.onHovernow receives a wrappedeventas the first parameter. The previous first parameter value is accessible viaevent.native.options.hover.onHover已删除,使用options.onHover。¥
options.hover.onHoverwas removed, useoptions.onHover.
# 刻度
¥Ticks
options.gridLines更名为options.grid¥
options.gridLineswas renamed tooptions.gridoptions.gridLines.offsetGridLines更名为options.grid.offset。¥
options.gridLines.offsetGridLineswas renamed tooptions.grid.offset.options.gridLines.tickMarkLength更名为options.grid.tickLength。¥
options.gridLines.tickMarkLengthwas renamed tooptions.grid.tickLength.options.ticks.fixedStepSize不再使用。使用options.ticks.stepSize。¥
options.ticks.fixedStepSizeis no longer used. Useoptions.ticks.stepSize.options.ticks.major和options.ticks.minor已替换为刻度字体的可编写脚本的选项。¥
options.ticks.majorandoptions.ticks.minorwere replaced with scriptable options for tick fonts.Chart.Ticks.formatters.linear更名为Chart.Ticks.formatters.numeric。¥
Chart.Ticks.formatters.linearwas renamed toChart.Ticks.formatters.numeric.options.ticks.backdropPaddingX和options.ticks.backdropPaddingY在径向线性刻度中被替换为options.ticks.backdropPadding。¥
options.ticks.backdropPaddingXandoptions.ticks.backdropPaddingYwere replaced withoptions.ticks.backdropPaddingin the radial linear scale.
# 工具提示
¥Tooltip
xLabel和yLabel已删除。请使用label和formattedValue¥
xLabelandyLabelwere removed. Please uselabelandformattedValuefilter选项现在将在调用时传递附加参数,并且应该具有方法签名function(tooltipItem, index, tooltipItems, data)¥The
filteroption will now be passed additional parameters when called and should have the method signaturefunction(tooltipItem, index, tooltipItems, data)custom回调现在采用具有tooltip和chart属性的上下文对象¥The
customcallback now takes a context object that hastooltipandchartproperties与工具提示选项相关的工具提示模型的所有属性都已移至
options属性中。¥All properties of tooltip model related to the tooltip options have been moved to reside within the
optionsproperty.回调不再被赋予
data参数。工具提示项参数改为包含图表和数据集¥The callbacks no longer are given a
dataparameter. The tooltip item parameter contains the chart and dataset instead工具提示项的
index参数重命名为dataIndex,value重命名为formattedValue¥The tooltip item's
indexparameter was renamed todataIndexandvaluewas renamed toformattedValuexPadding和yPadding选项合并为一个padding对象¥The
xPaddingandyPaddingoptions were merged into a singlepaddingobject
# 开发者迁移
¥Developer migration
虽然 Chart.js 3 的终端用户迁移相当简单,但开发者迁移可能更加复杂。如果有关迁移的提示有帮助,请在#dev Discord (opens new window) 通道中寻求帮助。
¥While the end-user migration for Chart.js 3 is fairly straight-forward, the developer migration can be more complicated. Please reach out for help in the #dev Discord (opens new window) channel if tips on migrating would be helpful.
一些最大的变化:
¥Some of the biggest things that have changed:
有一个完全重写且性能更高的动画系统。
¥There is a completely rewritten and more performant animation system.
Element._model和Element._view不再使用,现在直接在元素上设置属性。你将不得不使用方法getProps来访问大多数方法(例如inXRange/inYRange和getCenterPoint)中的这些属性。请查看 Chart.js 提供的元素 (opens new window) 以获取示例。¥
Element._modelandElement._vieware no longer used and properties are now set directly on the elements. You will have to use the methodgetPropsto access these properties inside most methods such asinXRange/inYRangeandgetCenterPoint. Please take a look at the Chart.js-provided elements (opens new window) for examples.在控制器中构建元素时,现在建议调用
updateElement来提供元素属性。还有getSharedOptions、includeOptions等方法被加入跳过冗余计算。请查看 Chart.js 提供的控制器 (opens new window) 以获取示例。¥When building the elements in a controller, it's now suggested to call
updateElementto provide the element properties. There are also methods such asgetSharedOptionsandincludeOptionsthat have been added to skip redundant computation. Please take a look at the Chart.js-provided controllers (opens new window) for examples.
缩放引入了一个新的解析 API。此 API 获取用户数据并将其转换为更标准的格式。E.g.它允许用户提供
string形式的数值数据,并在必要时将其转换为number。以前这是在渲染图表时即时完成的。如果用户以正确的格式提供数据,现在可以跳过它以获得更好的性能。如果你使用的是标准数据格式,如x/y,你可能不需要做任何事情。如果你使用自定义数据格式,则必须重写core.datasetController.js中的某些解析方法。可以在 chartjs-chart-financial (opens new window) 中找到一个示例,它使用{o, h, l, c}数据格式。¥Scales introduced a new parsing API. This API takes user data and converts it into a more standard format. E.g. it allows users to provide numeric data as a
stringand converts it to anumberwhere necessary. Previously this was done on the fly as charts were rendered. Now it's done up front with the ability to skip it for better performance if users provide data in the correct format. If you're using standard data format likex/yyou may not need to do anything. If you're using a custom data format you will have to override some of the parse methods incore.datasetController.js. An example can be found in chartjs-chart-financial (opens new window), which uses an{o, h, l, c}data format.
对更直接的控制器进行了一些更改,但会影响所有控制器:
¥A few changes were made to controllers that are more straight-forward, but will affect all controllers:
选项:
¥Options:
global已从 defaults 命名空间中删除,因为它是不必要的并且有时不一致¥
globalwas removed from the defaults namespace as it was unnecessary and sometimes inconsistent数据集默认值现在位于图表类型选项下,而不是相反。为了向后兼容而在 2.x 中引入时无法完成此操作。修复它消除了新图表开发者遇到的最大绊脚石
¥Dataset defaults are now under the chart type options instead of vice-versa. This was not able to be done when introduced in 2.x for backwards compatibility. Fixing it removes the biggest stumbling block that new chart developers encountered
需要按照终端用户迁移部分中的描述更新缩放默认选项(例如,
x而不是xAxes和y而不是yAxes)¥Scale default options need to be updated as described in the end user migration section (e.g.
xinstead ofxAxesandyinstead ofyAxes)
updateElement已更改为updateElements,并具有如下所述的新方法签名。这提供了性能增强,例如允许更轻松地重用所有元素共有的计算并减少函数调用的次数¥
updateElementwas changed toupdateElementsand has a new method signature as described below. This provides performance enhancements such as allowing easier reuse of computations that are common to all elements and reducing the number of function calls
# 删除
¥Removed
删除了以下属性和方法:
¥The following properties and methods were removed:
# 从图表中删除
¥Removed from Chart
Chart.animationServiceChart.activeChart.borderWidthChart.chart.chartChart.Bar。新图表通过new Chart创建并提供适当的type参数¥
Chart.Bar. New charts are created vianew Chartand providing the appropriatetypeparameterChart.Bubble。新图表通过new Chart创建并提供适当的type参数¥
Chart.Bubble. New charts are created vianew Chartand providing the appropriatetypeparameterChart.ChartChart.ControllerChart.Doughnut。新图表通过new Chart创建并提供适当的type参数¥
Chart.Doughnut. New charts are created vianew Chartand providing the appropriatetypeparameterChart.innerRadius现在在环形图、饼图和 polarArea 控制器上运行¥
Chart.innerRadiusnow lives on doughnut, pie, and polarArea controllersChart.lastActiveChart.Legend已移至Chart.plugins.legend._element并设为私有¥
Chart.Legendwas moved toChart.plugins.legend._elementand made privateChart.Line。新图表通过new Chart创建并提供适当的type参数¥
Chart.Line. New charts are created vianew Chartand providing the appropriatetypeparameterChart.LinearScaleBase现在必须导入,不能从Chart对象访问¥
Chart.LinearScaleBasenow must be imported and cannot be accessed off theChartobjectChart.offsetXChart.offsetYChart.outerRadius现在在环形图、饼图和 polarArea 控制器上运行¥
Chart.outerRadiusnow lives on doughnut, pie, and polarArea controllersChart.plugins已替换为Chart.registry。插件默认值现在在Chart.defaults.plugins[id]中。¥
Chart.pluginswas replaced withChart.registry. Plugin defaults are now inChart.defaults.plugins[id].Chart.plugins.register被Chart.register取代。¥
Chart.plugins.registerwas replaced byChart.register.Chart.PolarArea。新图表通过new Chart创建并提供适当的type参数¥
Chart.PolarArea. New charts are created vianew Chartand providing the appropriatetypeparameterChart.prototype.generateLegendChart.platform。它只包含disableCSSInjection。v3 中从未注入 CSS。¥
Chart.platform. It only containeddisableCSSInjection. CSS is never injected in v3.Chart.PluginBaseChart.Radar。新图表通过new Chart创建并提供适当的type参数¥
Chart.Radar. New charts are created vianew Chartand providing the appropriatetypeparameterChart.radiusLengthChart.scaleService已替换为Chart.registry。缩放默认值现在为Chart.defaults.scales[type]。¥
Chart.scaleServicewas replaced withChart.registry. Scale defaults are now inChart.defaults.scales[type].Chart.Scatter。新图表通过new Chart创建并提供适当的type参数¥
Chart.Scatter. New charts are created vianew Chartand providing the appropriatetypeparameterChart.typesChart.Title已移至Chart.plugins.title._element并设为私有¥
Chart.Titlewas moved toChart.plugins.title._elementand made privateChart.Tooltip现在由工具提示插件提供。可以从tooltipPlugin.positioners访问定位器¥
Chart.Tooltipis now provided by the tooltip plugin. The positioners can be accessed fromtooltipPlugin.positionersILayoutItem.minSize
# 从数据集控制器中删除
¥Removed from Dataset Controllers
BarController.getDatasetMeta().barDatasetController.addElementAndResetDatasetController.createMetaDataDatasetController.createMetaDatasetDoughnutController.getRingIndex
# 从元素中删除
¥Removed from Elements
Element.getAreaElement.heightElement.hidden已替换为图表级别状态,可用于getDataVisibility(index)/toggleDataVisibility(index)¥
Element.hiddenwas replaced by chart level status, usable withgetDataVisibility(index)/toggleDataVisibility(index)Element.initializeElement.inLabelRangeLine.calculatePointY
# 从助手中删除
¥Removed from Helpers
helpers.addEventhelpers.aliasPixelhelpers.arrayEqualshelpers.configMergehelpers.findIndexhelpers.findNextWherehelpers.findPreviousWherehelpers.extend。改用Object.assign¥
helpers.extend. UseObject.assigninsteadhelpers.getValueAtIndexOrDefault。请改用helpers.resolve。¥
helpers.getValueAtIndexOrDefault. Usehelpers.resolveinstead.helpers.indexOfhelpers.lineTohelpers.longestText已设为私有¥
helpers.longestTextwas made privatehelpers.maxhelpers.measureText已设为私有¥
helpers.measureTextwas made privatehelpers.minhelpers.nextItemhelpers.niceNumhelpers.numberOfLabelLineshelpers.previousItemhelpers.removeEventhelpers.roundedRecthelpers.scaleMergehelpers.where
# 从布局中删除
¥Removed from Layout
Layout.defaults
# 从秤中移除
¥Removed from Scales
LinearScaleBase.handleDirectionalChangesLogarithmicScale.minNotZeroScale.getRightValueScale.longestLabelWidthScale.longestTextCache现在是私有的¥
Scale.longestTextCacheis now privateScale.margins现在是私有的¥
Scale.marginsis now privateScale.mergeTicksOptionsScale.ticksAsNumbersScale.tickValues现在是私有的¥
Scale.tickValuesis now privateTimeScale.getLabelCapacity现在是私有的¥
TimeScale.getLabelCapacityis now privateTimeScale.tickFormatFunction现在是私有的¥
TimeScale.tickFormatFunctionis now private
# 从插件中删除(图例、标题和工具提示)
¥Removed from Plugins (Legend, Title, and Tooltip)
IPlugin.afterScaleUpdate。改用afterLayout¥
IPlugin.afterScaleUpdate. UseafterLayoutinsteadLegend.margins现在是私有的¥
Legend.marginsis now private图例
onClick、onHover和onLeave选项现在除了通过this隐式接收图例作为第三个参数¥Legend
onClick,onHover, andonLeaveoptions now receive the legend as the 3rd argument in addition to implicitly viathis图例
onClick、onHover和onLeave选项现在接收一个封装的event作为第一个参数。先前的第一个参数值可通过event.native访问。¥Legend
onClick,onHover, andonLeaveoptions now receive a wrappedeventas the first parameter. The previous first parameter value is accessible viaevent.native.Title.margins现在是私有的¥
Title.marginsis now private工具提示项的
x和y属性已替换为element。你可以改用element.x和element.y或element.tooltipPosition()。¥The tooltip item's
xandyattributes were replaced byelement. You can useelement.xandelement.yorelement.tooltipPosition()instead.
# 删除公共 API
¥Removal of Public APIs
删除了以下公共 API。
¥The following public APIs were removed.
getElementAtEvent替换为chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false)¥
getElementAtEventis replaced withchart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false)getElementsAtEvent替换为chart.getElementsAtEventForMode(e, 'index', { intersect: true }, false)¥
getElementsAtEventis replaced withchart.getElementsAtEventForMode(e, 'index', { intersect: true }, false)getElementsAtXAxis替换为chart.getElementsAtEventForMode(e, 'index', { intersect: false }, false)¥
getElementsAtXAxisis replaced withchart.getElementsAtEventForMode(e, 'index', { intersect: false }, false)getDatasetAtEvent替换为chart.getElementsAtEventForMode(e, 'dataset', { intersect: true }, false)¥
getDatasetAtEventis replaced withchart.getElementsAtEventForMode(e, 'dataset', { intersect: true }, false)
# 删除私有 API
¥Removal of private APIs
删除了以下私有 API。
¥The following private APIs were removed.
Chart._bufferedRenderChart._updatingChart.data.datasets[datasetIndex]._metaDatasetController._getIndexScaleIdDatasetController._getIndexScaleDatasetController._getValueScaleIdDatasetController._getValueScaleElement._ctxElement._modelElement._viewLogarithmicScale._valueOffsetTimeScale.getPixelForOffsetTimeScale.getLabelWidthTooltip._lastActive
# 更名
¥Renamed
在 v3 开发期间重命名了以下属性:
¥The following properties were renamed during v3 development:
Chart.Animation.animationObject更名为Chart.Animation¥
Chart.Animation.animationObjectwas renamed toChart.AnimationChart.Animation.chartInstance更名为Chart.Animation.chart¥
Chart.Animation.chartInstancewas renamed toChart.Animation.chartChart.canvasHelpers与Chart.helpers合并¥
Chart.canvasHelperswas merged withChart.helpersChart.elements.Arc更名为Chart.elements.ArcElement¥
Chart.elements.Arcwas renamed toChart.elements.ArcElementChart.elements.Line更名为Chart.elements.LineElement¥
Chart.elements.Linewas renamed toChart.elements.LineElementChart.elements.Point更名为Chart.elements.PointElement¥
Chart.elements.Pointwas renamed toChart.elements.PointElementChart.elements.Rectangle更名为Chart.elements.BarElement¥
Chart.elements.Rectanglewas renamed toChart.elements.BarElementChart.layoutService更名为Chart.layouts¥
Chart.layoutServicewas renamed toChart.layoutsChart.pluginService更名为Chart.plugins¥
Chart.pluginServicewas renamed toChart.pluginshelpers.callCallback更名为helpers.callback¥
helpers.callCallbackwas renamed tohelpers.callbackhelpers.drawRoundedRectangle更名为helpers.roundedRect¥
helpers.drawRoundedRectanglewas renamed tohelpers.roundedRecthelpers.getValueOrDefault更名为helpers.valueOrDefault¥
helpers.getValueOrDefaultwas renamed tohelpers.valueOrDefaultLayoutItem.fullWidth更名为LayoutItem.fullSize¥
LayoutItem.fullWidthwas renamed toLayoutItem.fullSizePoint.controlPointPreviousX更名为Point.cp1x¥
Point.controlPointPreviousXwas renamed toPoint.cp1xPoint.controlPointPreviousY更名为Point.cp1y¥
Point.controlPointPreviousYwas renamed toPoint.cp1yPoint.controlPointNextX更名为Point.cp2x¥
Point.controlPointNextXwas renamed toPoint.cp2xPoint.controlPointNextY更名为Point.cp2y¥
Point.controlPointNextYwas renamed toPoint.cp2yScale.calculateTickRotation更名为Scale.calculateLabelRotation¥
Scale.calculateTickRotationwas renamed toScale.calculateLabelRotationTooltip.options.legendColorBackgroupd更名为Tooltip.options.multiKeyBackground¥
Tooltip.options.legendColorBackgroupdwas renamed toTooltip.options.multiKeyBackground
# 重命名私有 API
¥Renamed private APIs
下面列出的私有 API 已重命名:
¥The private APIs listed below were renamed:
BarController.calculateBarIndexPixels更名为BarController._calculateBarIndexPixels¥
BarController.calculateBarIndexPixelswas renamed toBarController._calculateBarIndexPixelsBarController.calculateBarValuePixels更名为BarController._calculateBarValuePixels¥
BarController.calculateBarValuePixelswas renamed toBarController._calculateBarValuePixelsBarController.getStackCount更名为BarController._getStackCount¥
BarController.getStackCountwas renamed toBarController._getStackCountBarController.getStackIndex更名为BarController._getStackIndex¥
BarController.getStackIndexwas renamed toBarController._getStackIndexBarController.getRuler更名为BarController._getRuler¥
BarController.getRulerwas renamed toBarController._getRulerChart.destroyDatasetMeta更名为Chart._destroyDatasetMeta¥
Chart.destroyDatasetMetawas renamed toChart._destroyDatasetMetaChart.drawDataset更名为Chart._drawDataset¥
Chart.drawDatasetwas renamed toChart._drawDatasetChart.drawDatasets更名为Chart._drawDatasets¥
Chart.drawDatasetswas renamed toChart._drawDatasetsChart.eventHandler更名为Chart._eventHandler¥
Chart.eventHandlerwas renamed toChart._eventHandlerChart.handleEvent更名为Chart._handleEvent¥
Chart.handleEventwas renamed toChart._handleEventChart.initialize更名为Chart._initialize¥
Chart.initializewas renamed toChart._initializeChart.resetElements更名为Chart._resetElements¥
Chart.resetElementswas renamed toChart._resetElementsChart.unbindEvents更名为Chart._unbindEvents¥
Chart.unbindEventswas renamed toChart._unbindEventsChart.updateDataset更名为Chart._updateDataset¥
Chart.updateDatasetwas renamed toChart._updateDatasetChart.updateDatasets更名为Chart._updateDatasets¥
Chart.updateDatasetswas renamed toChart._updateDatasetsChart.updateLayout更名为Chart._updateLayout¥
Chart.updateLayoutwas renamed toChart._updateLayoutDatasetController.destroy更名为DatasetController._destroy¥
DatasetController.destroywas renamed toDatasetController._destroyDatasetController.insertElements更名为DatasetController._insertElements¥
DatasetController.insertElementswas renamed toDatasetController._insertElementsDatasetController.onDataPop更名为DatasetController._onDataPop¥
DatasetController.onDataPopwas renamed toDatasetController._onDataPopDatasetController.onDataPush更名为DatasetController._onDataPush¥
DatasetController.onDataPushwas renamed toDatasetController._onDataPushDatasetController.onDataShift更名为DatasetController._onDataShift¥
DatasetController.onDataShiftwas renamed toDatasetController._onDataShiftDatasetController.onDataSplice更名为DatasetController._onDataSplice¥
DatasetController.onDataSplicewas renamed toDatasetController._onDataSpliceDatasetController.onDataUnshift更名为DatasetController._onDataUnshift¥
DatasetController.onDataUnshiftwas renamed toDatasetController._onDataUnshiftDatasetController.removeElements更名为DatasetController._removeElements¥
DatasetController.removeElementswas renamed toDatasetController._removeElementsDatasetController.resyncElements更名为DatasetController._resyncElements¥
DatasetController.resyncElementswas renamed toDatasetController._resyncElementsLayoutItem.isFullWidth更名为LayoutItem.isFullSize¥
LayoutItem.isFullWidthwas renamed toLayoutItem.isFullSizeRadialLinearScale.setReductions更名为RadialLinearScale._setReductions¥
RadialLinearScale.setReductionswas renamed toRadialLinearScale._setReductionsRadialLinearScale.pointLabels更名为RadialLinearScale._pointLabels¥
RadialLinearScale.pointLabelswas renamed toRadialLinearScale._pointLabelsScale.handleMargins更名为Scale._handleMargins¥
Scale.handleMarginswas renamed toScale._handleMargins
# 变化
¥Changed
本节中列出的 API 在签名或行为方面与版本 2 相比发生了变化。
¥The APIs listed in this section have changed in signature or behaviour from version 2.
# 缩放的变化
¥Changed in Scales
Scale.getLabelForIndex被scale.getLabelForValue取代¥
Scale.getLabelForIndexwas replaced byscale.getLabelForValueScale.getPixelForValue现在只需要一个参数。对于TimeScale,该参数必须是自纪元以来的毫秒数。作为性能优化,它可能采用可选的第二个参数,给出数据点的索引。¥
Scale.getPixelForValuenow only requires one parameter. For theTimeScalethat parameter must be millis since the epoch. As a performance optimization, it may take an optional second parameter, giving the index of the data point.
# 刻度的变化
¥Changed in Ticks
Scale.afterBuildTicks现在像其他回调一样没有参数¥
Scale.afterBuildTicksnow has no parameters like the other callbacksScale.buildTicks现在有望返回刻度对象¥
Scale.buildTicksis now expected to return tick objectsScale.convertTicksToLabels更名为generateTickLabels。现在期望在作为输入给出的刻度上设置标签属性¥
Scale.convertTicksToLabelswas renamed togenerateTickLabels. It is now expected to set the label property on the ticks given as inputScale.ticks现在包含对象而不是字符串¥
Scale.ticksnow contains objects instead of strings启用
autoSkip选项后,Scale.ticks现在仅包含未跳过的分时而不是所有分时。¥When the
autoSkipoption is enabled,Scale.ticksnow contains only the non-skipped ticks instead of all ticks.刻度现在总是以单调递增的顺序生成
¥Ticks are now always generated in monotonically increasing order
# 时间尺度的改变
¥Changed in Time Scale
getValueForPixel现在返回自纪元以来的毫秒数¥
getValueForPixelnow returns milliseconds since the epoch
# 控制器的变化
¥Changed in Controllers
# 核心控制器
¥Core Controller
updateHoverStyle的第一个参数现在是包含element、datasetIndex和index的对象数组¥The first parameter to
updateHoverStyleis now an array of objects containing theelement,datasetIndex, andindex签名或
resize已更改,第一个silent参数已删除。¥The signature or
resizechanged, the firstsilentparameter was removed.
# 数据集控制器
¥Dataset Controllers
updateElement被updateElements取代,现在采用要更新的元素,start索引、count和mode¥
updateElementwas replaced withupdateElementsnow taking the elements to update, thestartindex,count, andmodesetHoverStyle和removeHoverStyle现在额外占用datasetIndex和index¥
setHoverStyleandremoveHoverStylenow additionally take thedatasetIndexandindex
# 互动的变化
¥Changed in Interactions
交互模式方法现在返回包含
element、datasetIndex和index的对象数组¥Interaction mode methods now return an array of objects containing the
element,datasetIndex, andindex
# 布局的变化
¥Changed in Layout
ILayoutItem.update不再有返回值¥
ILayoutItem.updateno longer has a return value
# 助手的变化
¥Changed in Helpers
所有助手现在都暴露在一个扁平层次结构中,例如,Chart.helpers.canvas.clipArea -> Chart.helpers.clipArea
¥All helpers are now exposed in a flat hierarchy, e.g., Chart.helpers.canvas.clipArea -> Chart.helpers.clipArea
# 画布助手
¥Canvas Helper
drawPoint的第二个参数现在是完整的选项对象,因此不再显式传递style、rotation和radius¥The second parameter to
drawPointis now the full options object, sostyle,rotation, andradiusare no longer passed explicitlyhelpers.getMaximumHeight被helpers.dom.getMaximumSize取代¥
helpers.getMaximumHeightwas replaced byhelpers.dom.getMaximumSizehelpers.getMaximumWidth被helpers.dom.getMaximumSize取代¥
helpers.getMaximumWidthwas replaced byhelpers.dom.getMaximumSizehelpers.clear已重命名为helpers.clearCanvas,现在将canvas和可选的ctx作为参数。¥
helpers.clearwas renamed tohelpers.clearCanvasand now takescanvasand optionallyctxas parameter(s).helpers.retinaScale接受可选的第三个参数forceStyle,它强制覆盖当前的画布样式。forceRatio不再退回到window.devicePixelRatio,而是默认为1。¥
helpers.retinaScaleaccepts optional third parameterforceStyle, which forces overriding current canvas style.forceRationo longer falls back towindow.devicePixelRatio, instead it defaults to1.
# 平台的变化
¥Changed in Platform
Chart.platform不再是图表使用的平台对象。每个图表实例现在都有一个单独的平台实例。¥
Chart.platformis no longer the platform object used by charts. Every chart instance now has a separate platform instance.Chart.platforms是一个包含两个可用平台类BasicPlatform和DomPlatform的对象。它还包含BasePlatform,一个所有平台都必须扩展的类。¥
Chart.platformsis an object that contains two usable platform classes,BasicPlatformandDomPlatform. It also containsBasePlatform, a class that all platforms must extend from.如果传入的 canvas 是
OffscreenCanvas的实例,则自动使用BasicPlatform。¥If the canvas passed in is an instance of
OffscreenCanvas, theBasicPlatformis automatically used.isAttached方法已添加到平台。¥
isAttachedmethod was added to platform.
# IPlugin 接口的变化
¥Changed in IPlugin interface
所有插件钩子都具有带有 3 个参数的统一签名:
chart、args和options。这意味着更改这些钩子的签名:beforeInit、afterInit、reset、beforeLayout、afterLayout、beforeRender、afterRender、beforeDraw、afterDraw、beforeDatasetsDraw、afterDatasetsDraw、beforeEvent、afterEvent、resize、destroy。¥All plugin hooks have unified signature with 3 arguments:
chart,argsandoptions. This means change in signature for these hooks:beforeInit,afterInit,reset,beforeLayout,afterLayout,beforeRender,afterRender,beforeDraw,afterDraw,beforeDatasetsDraw,afterDatasetsDraw,beforeEvent,afterEvent,resize,destroy.afterDatasetsUpdate、afterUpdate、beforeDatasetsUpdate和beforeUpdate现在接收args对象作为第二个参数。options参数始终是最后一个,因此从第 2 位移到了第 3 位。¥
afterDatasetsUpdate,afterUpdate,beforeDatasetsUpdate, andbeforeUpdatenow receiveargsobject as second argument.optionsargument is always the last and thus was moved from 2nd to 3rd place.afterEvent和beforeEvent现在接收一个封装的event作为第二个参数的event属性。原生事件可通过args.event.native获得。¥
afterEventandbeforeEventnow receive a wrappedeventas theeventproperty of the second argument. The native event is available viaargs.event.native.初始
resize不再沉默。意味着resize事件可以在beforeInit和afterInit之间触发¥Initial
resizeis no longer silent. Meaning thatresizeevent can fire betweenbeforeInitandafterInit新钩子:
install、start、stop和uninstall¥New hooks:
install,start,stop, anduninstallafterEvent应通过将args.changed设置为 true 来通知需要渲染的更改。因为args与所有插件共享,所以它应该只设置为 true 而不是 false。¥
afterEventshould notify about changes that need a render by settingargs.changedto true. Because theargsare shared with all plugins, it should only be set to true and not false.