# 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.js
andChart.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) 之一和相应的数据库。你不再需要从构建中排除时刻。¥
moment
is no longer specified as an npm dependency. If you are using thetime
ortimeseries
scales, 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
Chart
constructor 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
npm
module 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 callregister
if importing Chart.js via ascript
tag or from theauto
register path as annpm
module, 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
选项配置水平柱状图¥
horizontalBar
chart type was removed. Horizontal bar charts can be configured using the newindexAxis
option
# 选项
¥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.rectangle
is nowelements.bar
hover.animationDuration
现在配置在animation.active.duration
¥
hover.animationDuration
is now configured inanimation.active.duration
responsiveAnimationDuration
现在配置在animation.resize.duration
¥
responsiveAnimationDuration
is now configured inanimation.resize.duration
极地
elements.arc.angle
现在以度而不是弧度配置。¥Polar area
elements.arc.angle
is now configured in degrees instead of radians.极地
startAngle
选项现在与Radar
一致,0 在顶部,值以度为单位。默认值从-½π
更改为0
。¥Polar area
startAngle
option is now consistent withRadar
, 0 is at top and value is in degrees. Default is changed from-½π
to0
.Donut
rotation
选项现在以度为单位,0 位于顶部。默认值从-½π
更改为0
。¥Doughnut
rotation
option is now in degrees and 0 is at top. Default is changed from-½π
to0
.Donut
circumference
选项现在以度为单位。默认值从2π
更改为360
。¥Doughnut
circumference
option is now in degrees. Default is changed from2π
to360
.Donut
cutoutPercentage
已重命名为cutout
,并接受像素作为数字和百分比作为以%
结尾的字符串。¥Doughnut
cutoutPercentage
was renamed tocutout
and accepts pixels as number and percent as string ending with%
.scale
选项已被删除,取而代之的是options.scales.r
(或任何其他秤 ID,带有axis: 'r'
)¥
scale
option was removed in favor ofoptions.scales.r
(or any other scale id, withaxis: 'r'
)scales.[x/y]Axes
数组已删除。缩放现在直接配置为options.scales
对象,对象键为缩放 ID。¥
scales.[x/y]Axes
arrays were removed. Scales are now configured directly tooptions.scales
object with the object key being the scale Id.scales.[x/y]Axes.barPercentage
已移至数据集选项barPercentage
¥
scales.[x/y]Axes.barPercentage
was moved to dataset optionbarPercentage
scales.[x/y]Axes.barThickness
已移至数据集选项barThickness
¥
scales.[x/y]Axes.barThickness
was moved to dataset optionbarThickness
scales.[x/y]Axes.categoryPercentage
已移至数据集选项categoryPercentage
¥
scales.[x/y]Axes.categoryPercentage
was moved to dataset optioncategoryPercentage
scales.[x/y]Axes.maxBarThickness
已移至数据集选项maxBarThickness
¥
scales.[x/y]Axes.maxBarThickness
was moved to dataset optionmaxBarThickness
scales.[x/y]Axes.minBarLength
已移至数据集选项minBarLength
¥
scales.[x/y]Axes.minBarLength
was moved to dataset optionminBarLength
scales.[x/y]Axes.scaleLabel
更名为scales[id].title
¥
scales.[x/y]Axes.scaleLabel
was renamed toscales[id].title
scales.[x/y]Axes.scaleLabel.labelString
更名为scales[id].title.text
¥
scales.[x/y]Axes.scaleLabel.labelString
was renamed toscales[id].title.text
scales.[x/y]Axes.ticks.beginAtZero
更名为scales[id].beginAtZero
¥
scales.[x/y]Axes.ticks.beginAtZero
was renamed toscales[id].beginAtZero
scales.[x/y]Axes.ticks.max
更名为scales[id].max
¥
scales.[x/y]Axes.ticks.max
was renamed toscales[id].max
scales.[x/y]Axes.ticks.min
更名为scales[id].min
¥
scales.[x/y]Axes.ticks.min
was renamed toscales[id].min
scales.[x/y]Axes.ticks.reverse
更名为scales[id].reverse
¥
scales.[x/y]Axes.ticks.reverse
was renamed toscales[id].reverse
scales.[x/y]Axes.ticks.suggestedMax
更名为scales[id].suggestedMax
¥
scales.[x/y]Axes.ticks.suggestedMax
was renamed toscales[id].suggestedMax
scales.[x/y]Axes.ticks.suggestedMin
更名为scales[id].suggestedMin
¥
scales.[x/y]Axes.ticks.suggestedMin
was renamed toscales[id].suggestedMin
scales.[x/y]Axes.ticks.unitStepSize
已删除。使用scales[id].ticks.stepSize
¥
scales.[x/y]Axes.ticks.unitStepSize
was removed. Usescales[id].ticks.stepSize
scales.[x/y]Axes.ticks.userCallback
更名为scales[id].ticks.callback
¥
scales.[x/y]Axes.ticks.userCallback
was renamed toscales[id].ticks.callback
scales.[x/y]Axes.time.format
更名为scales[id].time.parser
¥
scales.[x/y]Axes.time.format
was renamed toscales[id].time.parser
scales.[x/y]Axes.time.max
更名为scales[id].max
¥
scales.[x/y]Axes.time.max
was renamed toscales[id].max
scales.[x/y]Axes.time.min
更名为scales[id].min
¥
scales.[x/y]Axes.time.min
was 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
steppedLine
was removed. Usestepped
图表选项
showLines
已重命名为showLine
以匹配数据集选项。¥The chart option
showLines
was renamed toshowLine
to match the dataset option.图表选项
startAngle
已移至radial
比例选项。¥The chart option
startAngle
was moved toradial
scale options.要覆盖图表实例中使用的平台类,请在配置对象中传递
platform: PlatformClass
。请注意,应该传递类,而不是类的实例。¥To override the platform class used in a chart instance, pass
platform: PlatformClass
in the config object. Note that the class should be passed, not an instance of the class.对于圆环图、饼图、极地区域图和雷达图,
aspectRatio
默认为 1¥
aspectRatio
defaults to 1 for doughnut, pie, polarArea, and radar charts默认情况下,
TimeScale
不再从对象数据中读取t
。默认属性为x
或y
,具体取决于方向。有关如何更改默认值的详细信息,请参阅 数据结构。¥
TimeScale
does not readt
from object data by default anymore. The default property isx
ory
, depending on the orientation. See data structures for details on how to change the default.tooltips
命名空间已重命名为tooltip
以匹配插件名称¥
tooltips
namespace was renamed totooltip
to match the plugin namelegend
、title
和tooltip
名称空间已从options
移至options.plugins
。¥
legend
,title
andtooltip
namespaces were moved fromoptions
tooptions.plugins
.tooltips.custom
更名为plugins.tooltip.external
¥
tooltips.custom
was renamed toplugins.tooltip.external
# 默认值
¥Defaults
global
命名空间已从defaults
中删除。所以Chart.defaults.global
现在是Chart.defaults
¥
global
namespace was removed fromdefaults
. SoChart.defaults.global
is nowChart.defaults
数据集控制器默认值已重新定位到
overrides
。例如Chart.defaults.line
现在是Chart.overrides.line
¥Dataset controller defaults were relocate to
overrides
. For exampleChart.defaults.line
is nowChart.overrides.line
default
前缀已从默认值中删除。例如Chart.defaults.global.defaultColor
现在是Chart.defaults.color
¥
default
prefix was removed from defaults. For exampleChart.defaults.global.defaultColor
is nowChart.defaults.color
defaultColor
拆分为color
、borderColor
和backgroundColor
¥
defaultColor
was split tocolor
,borderColor
andbackgroundColor
defaultFontColor
更名为color
¥
defaultFontColor
was renamed tocolor
defaultFontFamily
更名为font.family
¥
defaultFontFamily
was renamed tofont.family
defaultFontSize
更名为font.size
¥
defaultFontSize
was renamed tofont.size
defaultFontStyle
更名为font.style
¥
defaultFontStyle
was renamed tofont.style
defaultLineHeight
更名为font.lineHeight
¥
defaultLineHeight
was 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
,title
andtooltip
namespaces were moved fromChart.defaults
toChart.defaults.plugins
.elements.line.fill
默认值从true
更改为false
。¥
elements.line.fill
default changed fromtrue
tofalse
.折线图不再覆盖默认的
interaction
模式。默认值从'index'
更改为'nearest'
。¥Line charts no longer override the default
interaction
mode. 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 typetimeseries
was introduced in its place在时间尺度中,
autoSkip
现在默认启用,以与其他尺度保持一致¥In the time scale,
autoSkip
is 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
属性。请使用可编写脚本的选项¥
custom
attribute of elements was removed. Please use scriptable options可编写脚本的选项
context
对象的hover
属性已重命名为active
,以使其与数据标签插件保持一致。¥The
hover
property of scriptable optionscontext
object was renamed toactive
to 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.hover
andoptions.plugins.tooltip
now both extend fromoptions.interaction
. Defaults are defined atdefaults.interaction
level, so by default hover and tooltip interactions share the same mode etc.interactions
现在仅限于图表区域 + 允许溢出¥
interactions
are 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.onClick
is now limited to the chart areaoptions.onClick
和options.onHover
现在接收chart
实例作为第三个参数¥
options.onClick
andoptions.onHover
now receive thechart
instance as a 3rd argumentoptions.onHover
现在接收一个封装的event
作为第一个参数。先前的第一个参数值可通过event.native
访问。¥
options.onHover
now receives a wrappedevent
as the first parameter. The previous first parameter value is accessible viaevent.native
.options.hover.onHover
已删除,使用options.onHover
。¥
options.hover.onHover
was removed, useoptions.onHover
.
# 刻度
¥Ticks
options.gridLines
更名为options.grid
¥
options.gridLines
was renamed tooptions.grid
options.gridLines.offsetGridLines
更名为options.grid.offset
。¥
options.gridLines.offsetGridLines
was renamed tooptions.grid.offset
.options.gridLines.tickMarkLength
更名为options.grid.tickLength
。¥
options.gridLines.tickMarkLength
was renamed tooptions.grid.tickLength
.options.ticks.fixedStepSize
不再使用。使用options.ticks.stepSize
。¥
options.ticks.fixedStepSize
is no longer used. Useoptions.ticks.stepSize
.options.ticks.major
和options.ticks.minor
已替换为刻度字体的可编写脚本的选项。¥
options.ticks.major
andoptions.ticks.minor
were replaced with scriptable options for tick fonts.Chart.Ticks.formatters.linear
更名为Chart.Ticks.formatters.numeric
。¥
Chart.Ticks.formatters.linear
was renamed toChart.Ticks.formatters.numeric
.options.ticks.backdropPaddingX
和options.ticks.backdropPaddingY
在径向线性刻度中被替换为options.ticks.backdropPadding
。¥
options.ticks.backdropPaddingX
andoptions.ticks.backdropPaddingY
were replaced withoptions.ticks.backdropPadding
in the radial linear scale.
# 工具提示
¥Tooltip
xLabel
和yLabel
已删除。请使用label
和formattedValue
¥
xLabel
andyLabel
were removed. Please uselabel
andformattedValue
filter
选项现在将在调用时传递附加参数,并且应该具有方法签名function(tooltipItem, index, tooltipItems, data)
¥The
filter
option will now be passed additional parameters when called and should have the method signaturefunction(tooltipItem, index, tooltipItems, data)
custom
回调现在采用具有tooltip
和chart
属性的上下文对象¥The
custom
callback now takes a context object that hastooltip
andchart
properties与工具提示选项相关的工具提示模型的所有属性都已移至
options
属性中。¥All properties of tooltip model related to the tooltip options have been moved to reside within the
options
property.回调不再被赋予
data
参数。工具提示项参数改为包含图表和数据集¥The callbacks no longer are given a
data
parameter. The tooltip item parameter contains the chart and dataset instead工具提示项的
index
参数重命名为dataIndex
,value
重命名为formattedValue
¥The tooltip item's
index
parameter was renamed todataIndex
andvalue
was renamed toformattedValue
xPadding
和yPadding
选项合并为一个padding
对象¥The
xPadding
andyPadding
options were merged into a singlepadding
object
# 开发者迁移
¥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._model
andElement._view
are no longer used and properties are now set directly on the elements. You will have to use the methodgetProps
to access these properties inside most methods such asinXRange
/inYRange
andgetCenterPoint
. 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
updateElement
to provide the element properties. There are also methods such asgetSharedOptions
andincludeOptions
that 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
string
and converts it to anumber
where 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
/y
you 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 命名空间中删除,因为它是不必要的并且有时不一致¥
global
was 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.
x
instead ofxAxes
andy
instead ofyAxes
)
updateElement
已更改为updateElements
,并具有如下所述的新方法签名。这提供了性能增强,例如允许更轻松地重用所有元素共有的计算并减少函数调用的次数¥
updateElement
was changed toupdateElements
and 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.animationService
Chart.active
Chart.borderWidth
Chart.chart.chart
Chart.Bar
。新图表通过new Chart
创建并提供适当的type
参数¥
Chart.Bar
. New charts are created vianew Chart
and providing the appropriatetype
parameterChart.Bubble
。新图表通过new Chart
创建并提供适当的type
参数¥
Chart.Bubble
. New charts are created vianew Chart
and providing the appropriatetype
parameterChart.Chart
Chart.Controller
Chart.Doughnut
。新图表通过new Chart
创建并提供适当的type
参数¥
Chart.Doughnut
. New charts are created vianew Chart
and providing the appropriatetype
parameterChart.innerRadius
现在在环形图、饼图和 polarArea 控制器上运行¥
Chart.innerRadius
now lives on doughnut, pie, and polarArea controllersChart.lastActive
Chart.Legend
已移至Chart.plugins.legend._element
并设为私有¥
Chart.Legend
was moved toChart.plugins.legend._element
and made privateChart.Line
。新图表通过new Chart
创建并提供适当的type
参数¥
Chart.Line
. New charts are created vianew Chart
and providing the appropriatetype
parameterChart.LinearScaleBase
现在必须导入,不能从Chart
对象访问¥
Chart.LinearScaleBase
now must be imported and cannot be accessed off theChart
objectChart.offsetX
Chart.offsetY
Chart.outerRadius
现在在环形图、饼图和 polarArea 控制器上运行¥
Chart.outerRadius
now lives on doughnut, pie, and polarArea controllersChart.plugins
已替换为Chart.registry
。插件默认值现在在Chart.defaults.plugins[id]
中。¥
Chart.plugins
was replaced withChart.registry
. Plugin defaults are now inChart.defaults.plugins[id]
.Chart.plugins.register
被Chart.register
取代。¥
Chart.plugins.register
was replaced byChart.register
.Chart.PolarArea
。新图表通过new Chart
创建并提供适当的type
参数¥
Chart.PolarArea
. New charts are created vianew Chart
and providing the appropriatetype
parameterChart.prototype.generateLegend
Chart.platform
。它只包含disableCSSInjection
。v3 中从未注入 CSS。¥
Chart.platform
. It only containeddisableCSSInjection
. CSS is never injected in v3.Chart.PluginBase
Chart.Radar
。新图表通过new Chart
创建并提供适当的type
参数¥
Chart.Radar
. New charts are created vianew Chart
and providing the appropriatetype
parameterChart.radiusLength
Chart.scaleService
已替换为Chart.registry
。缩放默认值现在为Chart.defaults.scales[type]
。¥
Chart.scaleService
was replaced withChart.registry
. Scale defaults are now inChart.defaults.scales[type]
.Chart.Scatter
。新图表通过new Chart
创建并提供适当的type
参数¥
Chart.Scatter
. New charts are created vianew Chart
and providing the appropriatetype
parameterChart.types
Chart.Title
已移至Chart.plugins.title._element
并设为私有¥
Chart.Title
was moved toChart.plugins.title._element
and made privateChart.Tooltip
现在由工具提示插件提供。可以从tooltipPlugin.positioners
访问定位器¥
Chart.Tooltip
is now provided by the tooltip plugin. The positioners can be accessed fromtooltipPlugin.positioners
ILayoutItem.minSize
# 从数据集控制器中删除
¥Removed from Dataset Controllers
BarController.getDatasetMeta().bar
DatasetController.addElementAndReset
DatasetController.createMetaData
DatasetController.createMetaDataset
DoughnutController.getRingIndex
# 从元素中删除
¥Removed from Elements
Element.getArea
Element.height
Element.hidden
已替换为图表级别状态,可用于getDataVisibility(index)
/toggleDataVisibility(index)
¥
Element.hidden
was replaced by chart level status, usable withgetDataVisibility(index)
/toggleDataVisibility(index)
Element.initialize
Element.inLabelRange
Line.calculatePointY
# 从助手中删除
¥Removed from Helpers
helpers.addEvent
helpers.aliasPixel
helpers.arrayEquals
helpers.configMerge
helpers.findIndex
helpers.findNextWhere
helpers.findPreviousWhere
helpers.extend
。改用Object.assign
¥
helpers.extend
. UseObject.assign
insteadhelpers.getValueAtIndexOrDefault
。请改用helpers.resolve
。¥
helpers.getValueAtIndexOrDefault
. Usehelpers.resolve
instead.helpers.indexOf
helpers.lineTo
helpers.longestText
已设为私有¥
helpers.longestText
was made privatehelpers.max
helpers.measureText
已设为私有¥
helpers.measureText
was made privatehelpers.min
helpers.nextItem
helpers.niceNum
helpers.numberOfLabelLines
helpers.previousItem
helpers.removeEvent
helpers.roundedRect
helpers.scaleMerge
helpers.where
# 从布局中删除
¥Removed from Layout
Layout.defaults
# 从秤中移除
¥Removed from Scales
LinearScaleBase.handleDirectionalChanges
LogarithmicScale.minNotZero
Scale.getRightValue
Scale.longestLabelWidth
Scale.longestTextCache
现在是私有的¥
Scale.longestTextCache
is now privateScale.margins
现在是私有的¥
Scale.margins
is now privateScale.mergeTicksOptions
Scale.ticksAsNumbers
Scale.tickValues
现在是私有的¥
Scale.tickValues
is now privateTimeScale.getLabelCapacity
现在是私有的¥
TimeScale.getLabelCapacity
is now privateTimeScale.tickFormatFunction
现在是私有的¥
TimeScale.tickFormatFunction
is now private
# 从插件中删除(图例、标题和工具提示)
¥Removed from Plugins (Legend, Title, and Tooltip)
IPlugin.afterScaleUpdate
。改用afterLayout
¥
IPlugin.afterScaleUpdate
. UseafterLayout
insteadLegend.margins
现在是私有的¥
Legend.margins
is now private图例
onClick
、onHover
和onLeave
选项现在除了通过this
隐式接收图例作为第三个参数¥Legend
onClick
,onHover
, andonLeave
options now receive the legend as the 3rd argument in addition to implicitly viathis
图例
onClick
、onHover
和onLeave
选项现在接收一个封装的event
作为第一个参数。先前的第一个参数值可通过event.native
访问。¥Legend
onClick
,onHover
, andonLeave
options now receive a wrappedevent
as the first parameter. The previous first parameter value is accessible viaevent.native
.Title.margins
现在是私有的¥
Title.margins
is now private工具提示项的
x
和y
属性已替换为element
。你可以改用element.x
和element.y
或element.tooltipPosition()
。¥The tooltip item's
x
andy
attributes were replaced byelement
. You can useelement.x
andelement.y
orelement.tooltipPosition()
instead.
# 删除公共 API
¥Removal of Public APIs
删除了以下公共 API。
¥The following public APIs were removed.
getElementAtEvent
替换为chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false)
¥
getElementAtEvent
is replaced withchart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false)
getElementsAtEvent
替换为chart.getElementsAtEventForMode(e, 'index', { intersect: true }, false)
¥
getElementsAtEvent
is replaced withchart.getElementsAtEventForMode(e, 'index', { intersect: true }, false)
getElementsAtXAxis
替换为chart.getElementsAtEventForMode(e, 'index', { intersect: false }, false)
¥
getElementsAtXAxis
is replaced withchart.getElementsAtEventForMode(e, 'index', { intersect: false }, false)
getDatasetAtEvent
替换为chart.getElementsAtEventForMode(e, 'dataset', { intersect: true }, false)
¥
getDatasetAtEvent
is replaced withchart.getElementsAtEventForMode(e, 'dataset', { intersect: true }, false)
# 删除私有 API
¥Removal of private APIs
删除了以下私有 API。
¥The following private APIs were removed.
Chart._bufferedRender
Chart._updating
Chart.data.datasets[datasetIndex]._meta
DatasetController._getIndexScaleId
DatasetController._getIndexScale
DatasetController._getValueScaleId
DatasetController._getValueScale
Element._ctx
Element._model
Element._view
LogarithmicScale._valueOffset
TimeScale.getPixelForOffset
TimeScale.getLabelWidth
Tooltip._lastActive
# 更名
¥Renamed
在 v3 开发期间重命名了以下属性:
¥The following properties were renamed during v3 development:
Chart.Animation.animationObject
更名为Chart.Animation
¥
Chart.Animation.animationObject
was renamed toChart.Animation
Chart.Animation.chartInstance
更名为Chart.Animation.chart
¥
Chart.Animation.chartInstance
was renamed toChart.Animation.chart
Chart.canvasHelpers
与Chart.helpers
合并¥
Chart.canvasHelpers
was merged withChart.helpers
Chart.elements.Arc
更名为Chart.elements.ArcElement
¥
Chart.elements.Arc
was renamed toChart.elements.ArcElement
Chart.elements.Line
更名为Chart.elements.LineElement
¥
Chart.elements.Line
was renamed toChart.elements.LineElement
Chart.elements.Point
更名为Chart.elements.PointElement
¥
Chart.elements.Point
was renamed toChart.elements.PointElement
Chart.elements.Rectangle
更名为Chart.elements.BarElement
¥
Chart.elements.Rectangle
was renamed toChart.elements.BarElement
Chart.layoutService
更名为Chart.layouts
¥
Chart.layoutService
was renamed toChart.layouts
Chart.pluginService
更名为Chart.plugins
¥
Chart.pluginService
was renamed toChart.plugins
helpers.callCallback
更名为helpers.callback
¥
helpers.callCallback
was renamed tohelpers.callback
helpers.drawRoundedRectangle
更名为helpers.roundedRect
¥
helpers.drawRoundedRectangle
was renamed tohelpers.roundedRect
helpers.getValueOrDefault
更名为helpers.valueOrDefault
¥
helpers.getValueOrDefault
was renamed tohelpers.valueOrDefault
LayoutItem.fullWidth
更名为LayoutItem.fullSize
¥
LayoutItem.fullWidth
was renamed toLayoutItem.fullSize
Point.controlPointPreviousX
更名为Point.cp1x
¥
Point.controlPointPreviousX
was renamed toPoint.cp1x
Point.controlPointPreviousY
更名为Point.cp1y
¥
Point.controlPointPreviousY
was renamed toPoint.cp1y
Point.controlPointNextX
更名为Point.cp2x
¥
Point.controlPointNextX
was renamed toPoint.cp2x
Point.controlPointNextY
更名为Point.cp2y
¥
Point.controlPointNextY
was renamed toPoint.cp2y
Scale.calculateTickRotation
更名为Scale.calculateLabelRotation
¥
Scale.calculateTickRotation
was renamed toScale.calculateLabelRotation
Tooltip.options.legendColorBackgroupd
更名为Tooltip.options.multiKeyBackground
¥
Tooltip.options.legendColorBackgroupd
was renamed toTooltip.options.multiKeyBackground
# 重命名私有 API
¥Renamed private APIs
下面列出的私有 API 已重命名:
¥The private APIs listed below were renamed:
BarController.calculateBarIndexPixels
更名为BarController._calculateBarIndexPixels
¥
BarController.calculateBarIndexPixels
was renamed toBarController._calculateBarIndexPixels
BarController.calculateBarValuePixels
更名为BarController._calculateBarValuePixels
¥
BarController.calculateBarValuePixels
was renamed toBarController._calculateBarValuePixels
BarController.getStackCount
更名为BarController._getStackCount
¥
BarController.getStackCount
was renamed toBarController._getStackCount
BarController.getStackIndex
更名为BarController._getStackIndex
¥
BarController.getStackIndex
was renamed toBarController._getStackIndex
BarController.getRuler
更名为BarController._getRuler
¥
BarController.getRuler
was renamed toBarController._getRuler
Chart.destroyDatasetMeta
更名为Chart._destroyDatasetMeta
¥
Chart.destroyDatasetMeta
was renamed toChart._destroyDatasetMeta
Chart.drawDataset
更名为Chart._drawDataset
¥
Chart.drawDataset
was renamed toChart._drawDataset
Chart.drawDatasets
更名为Chart._drawDatasets
¥
Chart.drawDatasets
was renamed toChart._drawDatasets
Chart.eventHandler
更名为Chart._eventHandler
¥
Chart.eventHandler
was renamed toChart._eventHandler
Chart.handleEvent
更名为Chart._handleEvent
¥
Chart.handleEvent
was renamed toChart._handleEvent
Chart.initialize
更名为Chart._initialize
¥
Chart.initialize
was renamed toChart._initialize
Chart.resetElements
更名为Chart._resetElements
¥
Chart.resetElements
was renamed toChart._resetElements
Chart.unbindEvents
更名为Chart._unbindEvents
¥
Chart.unbindEvents
was renamed toChart._unbindEvents
Chart.updateDataset
更名为Chart._updateDataset
¥
Chart.updateDataset
was renamed toChart._updateDataset
Chart.updateDatasets
更名为Chart._updateDatasets
¥
Chart.updateDatasets
was renamed toChart._updateDatasets
Chart.updateLayout
更名为Chart._updateLayout
¥
Chart.updateLayout
was renamed toChart._updateLayout
DatasetController.destroy
更名为DatasetController._destroy
¥
DatasetController.destroy
was renamed toDatasetController._destroy
DatasetController.insertElements
更名为DatasetController._insertElements
¥
DatasetController.insertElements
was renamed toDatasetController._insertElements
DatasetController.onDataPop
更名为DatasetController._onDataPop
¥
DatasetController.onDataPop
was renamed toDatasetController._onDataPop
DatasetController.onDataPush
更名为DatasetController._onDataPush
¥
DatasetController.onDataPush
was renamed toDatasetController._onDataPush
DatasetController.onDataShift
更名为DatasetController._onDataShift
¥
DatasetController.onDataShift
was renamed toDatasetController._onDataShift
DatasetController.onDataSplice
更名为DatasetController._onDataSplice
¥
DatasetController.onDataSplice
was renamed toDatasetController._onDataSplice
DatasetController.onDataUnshift
更名为DatasetController._onDataUnshift
¥
DatasetController.onDataUnshift
was renamed toDatasetController._onDataUnshift
DatasetController.removeElements
更名为DatasetController._removeElements
¥
DatasetController.removeElements
was renamed toDatasetController._removeElements
DatasetController.resyncElements
更名为DatasetController._resyncElements
¥
DatasetController.resyncElements
was renamed toDatasetController._resyncElements
LayoutItem.isFullWidth
更名为LayoutItem.isFullSize
¥
LayoutItem.isFullWidth
was renamed toLayoutItem.isFullSize
RadialLinearScale.setReductions
更名为RadialLinearScale._setReductions
¥
RadialLinearScale.setReductions
was renamed toRadialLinearScale._setReductions
RadialLinearScale.pointLabels
更名为RadialLinearScale._pointLabels
¥
RadialLinearScale.pointLabels
was renamed toRadialLinearScale._pointLabels
Scale.handleMargins
更名为Scale._handleMargins
¥
Scale.handleMargins
was 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.getLabelForIndex
was replaced byscale.getLabelForValue
Scale.getPixelForValue
现在只需要一个参数。对于TimeScale
,该参数必须是自纪元以来的毫秒数。作为性能优化,它可能采用可选的第二个参数,给出数据点的索引。¥
Scale.getPixelForValue
now only requires one parameter. For theTimeScale
that 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.afterBuildTicks
now has no parameters like the other callbacksScale.buildTicks
现在有望返回刻度对象¥
Scale.buildTicks
is now expected to return tick objectsScale.convertTicksToLabels
更名为generateTickLabels
。现在期望在作为输入给出的刻度上设置标签属性¥
Scale.convertTicksToLabels
was renamed togenerateTickLabels
. It is now expected to set the label property on the ticks given as inputScale.ticks
现在包含对象而不是字符串¥
Scale.ticks
now contains objects instead of strings启用
autoSkip
选项后,Scale.ticks
现在仅包含未跳过的分时而不是所有分时。¥When the
autoSkip
option is enabled,Scale.ticks
now contains only the non-skipped ticks instead of all ticks.刻度现在总是以单调递增的顺序生成
¥Ticks are now always generated in monotonically increasing order
# 时间尺度的改变
¥Changed in Time Scale
getValueForPixel
现在返回自纪元以来的毫秒数¥
getValueForPixel
now returns milliseconds since the epoch
# 控制器的变化
¥Changed in Controllers
# 核心控制器
¥Core Controller
updateHoverStyle
的第一个参数现在是包含element
、datasetIndex
和index
的对象数组¥The first parameter to
updateHoverStyle
is now an array of objects containing theelement
,datasetIndex
, andindex
签名或
resize
已更改,第一个silent
参数已删除。¥The signature or
resize
changed, the firstsilent
parameter was removed.
# 数据集控制器
¥Dataset Controllers
updateElement
被updateElements
取代,现在采用要更新的元素,start
索引、count
和mode
¥
updateElement
was replaced withupdateElements
now taking the elements to update, thestart
index,count
, andmode
setHoverStyle
和removeHoverStyle
现在额外占用datasetIndex
和index
¥
setHoverStyle
andremoveHoverStyle
now additionally take thedatasetIndex
andindex
# 互动的变化
¥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.update
no 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
drawPoint
is now the full options object, sostyle
,rotation
, andradius
are no longer passed explicitlyhelpers.getMaximumHeight
被helpers.dom.getMaximumSize
取代¥
helpers.getMaximumHeight
was replaced byhelpers.dom.getMaximumSize
helpers.getMaximumWidth
被helpers.dom.getMaximumSize
取代¥
helpers.getMaximumWidth
was replaced byhelpers.dom.getMaximumSize
helpers.clear
已重命名为helpers.clearCanvas
,现在将canvas
和可选的ctx
作为参数。¥
helpers.clear
was renamed tohelpers.clearCanvas
and now takescanvas
and optionallyctx
as parameter(s).helpers.retinaScale
接受可选的第三个参数forceStyle
,它强制覆盖当前的画布样式。forceRatio
不再退回到window.devicePixelRatio
,而是默认为1
。¥
helpers.retinaScale
accepts optional third parameterforceStyle
, which forces overriding current canvas style.forceRatio
no longer falls back towindow.devicePixelRatio
, instead it defaults to1
.
# 平台的变化
¥Changed in Platform
Chart.platform
不再是图表使用的平台对象。每个图表实例现在都有一个单独的平台实例。¥
Chart.platform
is no longer the platform object used by charts. Every chart instance now has a separate platform instance.Chart.platforms
是一个包含两个可用平台类BasicPlatform
和DomPlatform
的对象。它还包含BasePlatform
,一个所有平台都必须扩展的类。¥
Chart.platforms
is an object that contains two usable platform classes,BasicPlatform
andDomPlatform
. It also containsBasePlatform
, a class that all platforms must extend from.如果传入的 canvas 是
OffscreenCanvas
的实例,则自动使用BasicPlatform
。¥If the canvas passed in is an instance of
OffscreenCanvas
, theBasicPlatform
is automatically used.isAttached
方法已添加到平台。¥
isAttached
method 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
,args
andoptions
. 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
, andbeforeUpdate
now receiveargs
object as second argument.options
argument is always the last and thus was moved from 2nd to 3rd place.afterEvent
和beforeEvent
现在接收一个封装的event
作为第二个参数的event
属性。原生事件可通过args.event.native
获得。¥
afterEvent
andbeforeEvent
now receive a wrappedevent
as theevent
property of the second argument. The native event is available viaargs.event.native
.初始
resize
不再沉默。意味着resize
事件可以在beforeInit
和afterInit
之间触发¥Initial
resize
is no longer silent. Meaning thatresize
event can fire betweenbeforeInit
andafterInit
新钩子:
install
、start
、stop
和uninstall
¥New hooks:
install
,start
,stop
, anduninstall
afterEvent
应通过将args.changed
设置为 true 来通知需要渲染的更改。因为args
与所有插件共享,所以它应该只设置为 true 而不是 false。¥
afterEvent
should notify about changes that need a render by settingargs.changed
to true. Because theargs
are shared with all plugins, it should only be set to true and not false.