# 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.jsChart.bundle.min.js。如果你正在使用这些构建,请参阅 installationintegration 文档以了解有关设置 Chart.js 的推荐方法的详细信息。

    ¥Chart.js is no longer providing the Chart.bundle.js and Chart.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 依赖。如果你使用的是 timetimeseries 秤,则必须包括 可用的适配器 (opens new window) 之一和相应的数据库。你不再需要从构建中排除时刻。

    ¥moment is no longer specified as an npm dependency. If you are using the time or timeseries 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 use

  • Chart.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 call register if importing Chart.js via a script tag or from the auto register path as an npm 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 new indexAxis 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 now elements.bar

  • hover.animationDuration 现在配置在 animation.active.duration

    ¥hover.animationDuration is now configured in animation.active.duration

  • responsiveAnimationDuration 现在配置在 animation.resize.duration

    ¥responsiveAnimationDuration is now configured in animation.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 with Radar, 0 is at top and value is in degrees. Default is changed from -½π to 0.

  • Donut rotation 选项现在以度为单位,0 位于顶部。默认值从 -½π 更改为 0

    ¥Doughnut rotation option is now in degrees and 0 is at top. Default is changed from -½π to 0.

  • Donut circumference 选项现在以度为单位。默认值从 更改为 360

    ¥Doughnut circumference option is now in degrees. Default is changed from to 360.

  • Donut cutoutPercentage 已重命名为 cutout,并接受像素作为数字和百分比作为以 % 结尾的字符串。

    ¥Doughnut cutoutPercentage was renamed to cutoutand accepts pixels as number and percent as string ending with %.

  • scale 选项已被删除,取而代之的是 options.scales.r(或任何其他秤 ID,带有 axis: 'r'

    ¥scale option was removed in favor of options.scales.r (or any other scale id, with axis: 'r')

  • scales.[x/y]Axes 数组已删除。缩放现在直接配置为 options.scales 对象,对象键为缩放 ID。

    ¥scales.[x/y]Axes arrays were removed. Scales are now configured directly to options.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 option barPercentage

  • scales.[x/y]Axes.barThickness 已移至数据集选项 barThickness

    ¥scales.[x/y]Axes.barThickness was moved to dataset option barThickness

  • scales.[x/y]Axes.categoryPercentage 已移至数据集选项 categoryPercentage

    ¥scales.[x/y]Axes.categoryPercentage was moved to dataset option categoryPercentage

  • scales.[x/y]Axes.maxBarThickness 已移至数据集选项 maxBarThickness

    ¥scales.[x/y]Axes.maxBarThickness was moved to dataset option maxBarThickness

  • scales.[x/y]Axes.minBarLength 已移至数据集选项 minBarLength

    ¥scales.[x/y]Axes.minBarLength was moved to dataset option minBarLength

  • scales.[x/y]Axes.scaleLabel 更名为 scales[id].title

    ¥scales.[x/y]Axes.scaleLabel was renamed to scales[id].title

  • scales.[x/y]Axes.scaleLabel.labelString 更名为 scales[id].title.text

    ¥scales.[x/y]Axes.scaleLabel.labelString was renamed to scales[id].title.text

  • scales.[x/y]Axes.ticks.beginAtZero 更名为 scales[id].beginAtZero

    ¥scales.[x/y]Axes.ticks.beginAtZero was renamed to scales[id].beginAtZero

  • scales.[x/y]Axes.ticks.max 更名为 scales[id].max

    ¥scales.[x/y]Axes.ticks.max was renamed to scales[id].max

  • scales.[x/y]Axes.ticks.min 更名为 scales[id].min

    ¥scales.[x/y]Axes.ticks.min was renamed to scales[id].min

  • scales.[x/y]Axes.ticks.reverse 更名为 scales[id].reverse

    ¥scales.[x/y]Axes.ticks.reverse was renamed to scales[id].reverse

  • scales.[x/y]Axes.ticks.suggestedMax 更名为 scales[id].suggestedMax

    ¥scales.[x/y]Axes.ticks.suggestedMax was renamed to scales[id].suggestedMax

  • scales.[x/y]Axes.ticks.suggestedMin 更名为 scales[id].suggestedMin

    ¥scales.[x/y]Axes.ticks.suggestedMin was renamed to scales[id].suggestedMin

  • scales.[x/y]Axes.ticks.unitStepSize 已删除。使用 scales[id].ticks.stepSize

    ¥scales.[x/y]Axes.ticks.unitStepSize was removed. Use scales[id].ticks.stepSize

  • scales.[x/y]Axes.ticks.userCallback 更名为 scales[id].ticks.callback

    ¥scales.[x/y]Axes.ticks.userCallback was renamed to scales[id].ticks.callback

  • scales.[x/y]Axes.time.format 更名为 scales[id].time.parser

    ¥scales.[x/y]Axes.time.format was renamed to scales[id].time.parser

  • scales.[x/y]Axes.time.max 更名为 scales[id].max

    ¥scales.[x/y]Axes.time.max was renamed to scales[id].max

  • scales.[x/y]Axes.time.min 更名为 scales[id].min

    ¥scales.[x/y]Axes.time.min was renamed to scales[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. Use stepped

  • 图表选项 showLines 已重命名为 showLine 以匹配数据集选项。

    ¥The chart option showLines was renamed to showLine to match the dataset option.

  • 图表选项 startAngle 已移至 radial 比例选项。

    ¥The chart option startAngle was moved to radial 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。默认属性为 xy,具体取决于方向。有关如何更改默认值的详细信息,请参阅 数据结构

    ¥TimeScale does not read t from object data by default anymore. The default property is x or y, depending on the orientation. See data structures for details on how to change the default.

  • tooltips 命名空间已重命名为 tooltip 以匹配插件名称

    ¥tooltips namespace was renamed to tooltip to match the plugin name

  • legendtitletooltip 名称空间已从 options 移至 options.plugins

    ¥legend, title and tooltip namespaces were moved from options to options.plugins.

  • tooltips.custom 更名为 plugins.tooltip.external

    ¥tooltips.custom was renamed to plugins.tooltip.external

# 默认值

¥Defaults

  • global 命名空间已从 defaults 中删除。所以 Chart.defaults.global 现在是 Chart.defaults

    ¥global namespace was removed from defaults. So Chart.defaults.global is now Chart.defaults

  • 数据集控制器默认值已重新定位到 overrides。例如 Chart.defaults.line 现在是 Chart.overrides.line

    ¥Dataset controller defaults were relocate to overrides. For example Chart.defaults.line is now Chart.overrides.line

  • default 前缀已从默认值中删除。例如 Chart.defaults.global.defaultColor 现在是 Chart.defaults.color

    ¥default prefix was removed from defaults. For example Chart.defaults.global.defaultColor is now Chart.defaults.color

  • defaultColor 拆分为 colorborderColorbackgroundColor

    ¥defaultColor was split to color, borderColor and backgroundColor

  • defaultFontColor 更名为 color

    ¥defaultFontColor was renamed to color

  • defaultFontFamily 更名为 font.family

    ¥defaultFontFamily was renamed to font.family

  • defaultFontSize 更名为 font.size

    ¥defaultFontSize was renamed to font.size

  • defaultFontStyle 更名为 font.style

    ¥defaultFontStyle was renamed to font.style

  • defaultLineHeight 更名为 font.lineHeight

    ¥defaultLineHeight was renamed to font.lineHeight

  • 水平条默认工具提示模式已从 'index' 更改为 'nearest' 以匹配垂直柱状图

    ¥Horizontal Bar default tooltip mode was changed from 'index' to 'nearest' to match vertical bar charts

  • legendtitletooltip 名称空间已从 Chart.defaults 移至 Chart.defaults.plugins

    ¥legend, title and tooltip namespaces were moved from Chart.defaults to Chart.defaults.plugins.

  • elements.line.fill 默认值从 true 更改为 false

    ¥elements.line.fill default changed from true to false.

  • 折线图不再覆盖默认的 interaction 模式。默认值从 'index' 更改为 'nearest'

    ¥Line charts no longer override the default interaction mode. Default is changed from 'index' to 'nearest'.

# 标尺

¥Scales

比例尺的配置选项是 v3 中最大的变化。xAxesyAxes 数组被删除,轴选项是现在由刻度 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 type timeseries 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 options context object was renamed to active to align it with the datalabels plugin.

# 交互

¥Interactions

  • 为了允许 DRY 配置,添加了通用交互选项的根选项范围。options.hoveroptions.plugins.tooltip 现在都从 options.interaction 继承而来。默认值在 defaults.interaction 级别定义,因此默认情况下悬停和工具提示交互共享相同的模式等。

    ¥To allow DRY configuration, a root options scope for common interaction options was added. options.hover and options.plugins.tooltip now both extend from options.interaction. Defaults are defined at defaults.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 area

  • options.onClickoptions.onHover 现在接收 chart 实例作为第三个参数

    ¥options.onClick and options.onHover now receive the chart instance as a 3rd argument

  • options.onHover 现在接收一个封装的 event 作为第一个参数。先前的第一个参数值可通过 event.native 访问。

    ¥options.onHover now receives a wrapped event as the first parameter. The previous first parameter value is accessible via event.native.

  • options.hover.onHover 已删除,使用 options.onHover

    ¥options.hover.onHover was removed, use options.onHover.

# 刻度

¥Ticks

  • options.gridLines 更名为 options.grid

    ¥options.gridLines was renamed to options.grid

  • options.gridLines.offsetGridLines 更名为 options.grid.offset

    ¥options.gridLines.offsetGridLines was renamed to options.grid.offset.

  • options.gridLines.tickMarkLength 更名为 options.grid.tickLength

    ¥options.gridLines.tickMarkLength was renamed to options.grid.tickLength.

  • options.ticks.fixedStepSize 不再使用。使用 options.ticks.stepSize

    ¥options.ticks.fixedStepSize is no longer used. Use options.ticks.stepSize.

  • options.ticks.majoroptions.ticks.minor 已替换为刻度字体的可编写脚本的选项。

    ¥options.ticks.major and options.ticks.minor were replaced with scriptable options for tick fonts.

  • Chart.Ticks.formatters.linear 更名为 Chart.Ticks.formatters.numeric

    ¥Chart.Ticks.formatters.linear was renamed to Chart.Ticks.formatters.numeric.

  • options.ticks.backdropPaddingXoptions.ticks.backdropPaddingY 在径向线性刻度中被替换为 options.ticks.backdropPadding

    ¥options.ticks.backdropPaddingX and options.ticks.backdropPaddingY were replaced with options.ticks.backdropPadding in the radial linear scale.

# 工具提示

¥Tooltip

  • xLabelyLabel 已删除。请使用 labelformattedValue

    ¥xLabel and yLabel were removed. Please use label and formattedValue

  • filter 选项现在将在调用时传递附加参数,并且应该具有方法签名 function(tooltipItem, index, tooltipItems, data)

    ¥The filter option will now be passed additional parameters when called and should have the method signature function(tooltipItem, index, tooltipItems, data)

  • custom 回调现在采用具有 tooltipchart 属性的上下文对象

    ¥The custom callback now takes a context object that has tooltip and chart 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 参数重命名为 dataIndexvalue 重命名为 formattedValue

    ¥The tooltip item's index parameter was renamed to dataIndex and value was renamed to formattedValue

  • xPaddingyPadding 选项合并为一个 padding 对象

    ¥The xPadding and yPadding options were merged into a single padding 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._modelElement._view 不再使用,现在直接在元素上设置属性。你将不得不使用方法 getProps 来访问大多数方法(例如 inXRange/inYRangegetCenterPoint)中的这些属性。请查看 Chart.js 提供的元素 (opens new window) 以获取示例。

      ¥Element._model and Element._view are no longer used and properties are now set directly on the elements. You will have to use the method getProps to access these properties inside most methods such as inXRange/inYRange and getCenterPoint. Please take a look at the Chart.js-provided elements (opens new window) for examples.

    • 在控制器中构建元素时,现在建议调用 updateElement 来提供元素属性。还有 getSharedOptionsincludeOptions 等方法被加入跳过冗余计算。请查看 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 as getSharedOptions and includeOptions 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 a number 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 like x/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 in core.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 而不是 xAxesy 而不是 yAxes

      ¥Scale default options need to be updated as described in the end user migration section (e.g. x instead of xAxes and y instead of yAxes)

  • updateElement 已更改为 updateElements,并具有如下所述的新方法签名。这提供了性能增强,例如允许更轻松地重用所有元素共有的计算并减少函数调用的次数

    ¥updateElement was changed to updateElements 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 via new Chart and providing the appropriate type parameter

  • Chart.Bubble。新图表通过 new Chart 创建并提供适当的 type 参数

    ¥Chart.Bubble. New charts are created via new Chart and providing the appropriate type parameter

  • Chart.Chart

  • Chart.Controller

  • Chart.Doughnut。新图表通过 new Chart 创建并提供适当的 type 参数

    ¥Chart.Doughnut. New charts are created via new Chart and providing the appropriate type parameter

  • Chart.innerRadius 现在在环形图、饼图和 polarArea 控制器上运行

    ¥Chart.innerRadius now lives on doughnut, pie, and polarArea controllers

  • Chart.lastActive

  • Chart.Legend 已移至 Chart.plugins.legend._element 并设为私有

    ¥Chart.Legend was moved to Chart.plugins.legend._element and made private

  • Chart.Line。新图表通过 new Chart 创建并提供适当的 type 参数

    ¥Chart.Line. New charts are created via new Chart and providing the appropriate type parameter

  • Chart.LinearScaleBase 现在必须导入,不能从 Chart 对象访问

    ¥Chart.LinearScaleBase now must be imported and cannot be accessed off the Chart object

  • Chart.offsetX

  • Chart.offsetY

  • Chart.outerRadius 现在在环形图、饼图和 polarArea 控制器上运行

    ¥Chart.outerRadius now lives on doughnut, pie, and polarArea controllers

  • Chart.plugins 已替换为 Chart.registry。插件默认值现在在 Chart.defaults.plugins[id] 中。

    ¥Chart.plugins was replaced with Chart.registry. Plugin defaults are now in Chart.defaults.plugins[id].

  • Chart.plugins.registerChart.register 取代。

    ¥Chart.plugins.register was replaced by Chart.register.

  • Chart.PolarArea。新图表通过 new Chart 创建并提供适当的 type 参数

    ¥Chart.PolarArea. New charts are created via new Chart and providing the appropriate type parameter

  • Chart.prototype.generateLegend

  • Chart.platform。它只包含 disableCSSInjection。v3 中从未注入 CSS。

    ¥Chart.platform. It only contained disableCSSInjection. CSS is never injected in v3.

  • Chart.PluginBase

  • Chart.Radar。新图表通过 new Chart 创建并提供适当的 type 参数

    ¥Chart.Radar. New charts are created via new Chart and providing the appropriate type parameter

  • Chart.radiusLength

  • Chart.scaleService 已替换为 Chart.registry。缩放默认值现在为 Chart.defaults.scales[type]

    ¥Chart.scaleService was replaced with Chart.registry. Scale defaults are now in Chart.defaults.scales[type].

  • Chart.Scatter。新图表通过 new Chart 创建并提供适当的 type 参数

    ¥Chart.Scatter. New charts are created via new Chart and providing the appropriate type parameter

  • Chart.types

  • Chart.Title 已移至 Chart.plugins.title._element 并设为私有

    ¥Chart.Title was moved to Chart.plugins.title._element and made private

  • Chart.Tooltip 现在由工具提示插件提供。可以从 tooltipPlugin.positioners 访问定位器

    ¥Chart.Tooltip is now provided by the tooltip plugin. The positioners can be accessed from tooltipPlugin.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 with getDataVisibility(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. Use Object.assign instead

  • helpers.getValueAtIndexOrDefault。请改用 helpers.resolve

    ¥helpers.getValueAtIndexOrDefault. Use helpers.resolve instead.

  • helpers.indexOf

  • helpers.lineTo

  • helpers.longestText 已设为私有

    ¥helpers.longestText was made private

  • helpers.max

  • helpers.measureText 已设为私有

    ¥helpers.measureText was made private

  • helpers.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 private

  • Scale.margins 现在是私有的

    ¥Scale.margins is now private

  • Scale.mergeTicksOptions

  • Scale.ticksAsNumbers

  • Scale.tickValues 现在是私有的

    ¥Scale.tickValues is now private

  • TimeScale.getLabelCapacity 现在是私有的

    ¥TimeScale.getLabelCapacity is now private

  • TimeScale.tickFormatFunction 现在是私有的

    ¥TimeScale.tickFormatFunction is now private

# 从插件中删除(图例、标题和工具提示)

¥Removed from Plugins (Legend, Title, and Tooltip)

  • IPlugin.afterScaleUpdate。改用 afterLayout

    ¥IPlugin.afterScaleUpdate. Use afterLayout instead

  • Legend.margins 现在是私有的

    ¥Legend.margins is now private

  • 图例 onClickonHoveronLeave 选项现在除了通过 this 隐式接收图例作为第三个参数

    ¥Legend onClick, onHover, and onLeave options now receive the legend as the 3rd argument in addition to implicitly via this

  • 图例 onClickonHoveronLeave 选项现在接收一个封装的 event 作为第一个参数。先前的第一个参数值可通过 event.native 访问。

    ¥Legend onClick, onHover, and onLeave options now receive a wrapped event as the first parameter. The previous first parameter value is accessible via event.native.

  • Title.margins 现在是私有的

    ¥Title.margins is now private

  • 工具提示项的 xy 属性已替换为 element。你可以改用 element.xelement.yelement.tooltipPosition()

    ¥The tooltip item's x and y attributes were replaced by element. You can use element.x and element.y or element.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 with chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false)

  • getElementsAtEvent 替换为 chart.getElementsAtEventForMode(e, 'index', { intersect: true }, false)

    ¥getElementsAtEvent is replaced with chart.getElementsAtEventForMode(e, 'index', { intersect: true }, false)

  • getElementsAtXAxis 替换为 chart.getElementsAtEventForMode(e, 'index', { intersect: false }, false)

    ¥getElementsAtXAxis is replaced with chart.getElementsAtEventForMode(e, 'index', { intersect: false }, false)

  • getDatasetAtEvent 替换为 chart.getElementsAtEventForMode(e, 'dataset', { intersect: true }, false)

    ¥getDatasetAtEvent is replaced with chart.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 to Chart.Animation

  • Chart.Animation.chartInstance 更名为 Chart.Animation.chart

    ¥Chart.Animation.chartInstance was renamed to Chart.Animation.chart

  • Chart.canvasHelpersChart.helpers 合并

    ¥Chart.canvasHelpers was merged with Chart.helpers

  • Chart.elements.Arc 更名为 Chart.elements.ArcElement

    ¥Chart.elements.Arc was renamed to Chart.elements.ArcElement

  • Chart.elements.Line 更名为 Chart.elements.LineElement

    ¥Chart.elements.Line was renamed to Chart.elements.LineElement

  • Chart.elements.Point 更名为 Chart.elements.PointElement

    ¥Chart.elements.Point was renamed to Chart.elements.PointElement

  • Chart.elements.Rectangle 更名为 Chart.elements.BarElement

    ¥Chart.elements.Rectangle was renamed to Chart.elements.BarElement

  • Chart.layoutService 更名为 Chart.layouts

    ¥Chart.layoutService was renamed to Chart.layouts

  • Chart.pluginService 更名为 Chart.plugins

    ¥Chart.pluginService was renamed to Chart.plugins

  • helpers.callCallback 更名为 helpers.callback

    ¥helpers.callCallback was renamed to helpers.callback

  • helpers.drawRoundedRectangle 更名为 helpers.roundedRect

    ¥helpers.drawRoundedRectangle was renamed to helpers.roundedRect

  • helpers.getValueOrDefault 更名为 helpers.valueOrDefault

    ¥helpers.getValueOrDefault was renamed to helpers.valueOrDefault

  • LayoutItem.fullWidth 更名为 LayoutItem.fullSize

    ¥LayoutItem.fullWidth was renamed to LayoutItem.fullSize

  • Point.controlPointPreviousX 更名为 Point.cp1x

    ¥Point.controlPointPreviousX was renamed to Point.cp1x

  • Point.controlPointPreviousY 更名为 Point.cp1y

    ¥Point.controlPointPreviousY was renamed to Point.cp1y

  • Point.controlPointNextX 更名为 Point.cp2x

    ¥Point.controlPointNextX was renamed to Point.cp2x

  • Point.controlPointNextY 更名为 Point.cp2y

    ¥Point.controlPointNextY was renamed to Point.cp2y

  • Scale.calculateTickRotation 更名为 Scale.calculateLabelRotation

    ¥Scale.calculateTickRotation was renamed to Scale.calculateLabelRotation

  • Tooltip.options.legendColorBackgroupd 更名为 Tooltip.options.multiKeyBackground

    ¥Tooltip.options.legendColorBackgroupd was renamed to Tooltip.options.multiKeyBackground

# 重命名私有 API

¥Renamed private APIs

下面列出的私有 API 已重命名:

¥The private APIs listed below were renamed:

  • BarController.calculateBarIndexPixels 更名为 BarController._calculateBarIndexPixels

    ¥BarController.calculateBarIndexPixels was renamed to BarController._calculateBarIndexPixels

  • BarController.calculateBarValuePixels 更名为 BarController._calculateBarValuePixels

    ¥BarController.calculateBarValuePixels was renamed to BarController._calculateBarValuePixels

  • BarController.getStackCount 更名为 BarController._getStackCount

    ¥BarController.getStackCount was renamed to BarController._getStackCount

  • BarController.getStackIndex 更名为 BarController._getStackIndex

    ¥BarController.getStackIndex was renamed to BarController._getStackIndex

  • BarController.getRuler 更名为 BarController._getRuler

    ¥BarController.getRuler was renamed to BarController._getRuler

  • Chart.destroyDatasetMeta 更名为 Chart._destroyDatasetMeta

    ¥Chart.destroyDatasetMeta was renamed to Chart._destroyDatasetMeta

  • Chart.drawDataset 更名为 Chart._drawDataset

    ¥Chart.drawDataset was renamed to Chart._drawDataset

  • Chart.drawDatasets 更名为 Chart._drawDatasets

    ¥Chart.drawDatasets was renamed to Chart._drawDatasets

  • Chart.eventHandler 更名为 Chart._eventHandler

    ¥Chart.eventHandler was renamed to Chart._eventHandler

  • Chart.handleEvent 更名为 Chart._handleEvent

    ¥Chart.handleEvent was renamed to Chart._handleEvent

  • Chart.initialize 更名为 Chart._initialize

    ¥Chart.initialize was renamed to Chart._initialize

  • Chart.resetElements 更名为 Chart._resetElements

    ¥Chart.resetElements was renamed to Chart._resetElements

  • Chart.unbindEvents 更名为 Chart._unbindEvents

    ¥Chart.unbindEvents was renamed to Chart._unbindEvents

  • Chart.updateDataset 更名为 Chart._updateDataset

    ¥Chart.updateDataset was renamed to Chart._updateDataset

  • Chart.updateDatasets 更名为 Chart._updateDatasets

    ¥Chart.updateDatasets was renamed to Chart._updateDatasets

  • Chart.updateLayout 更名为 Chart._updateLayout

    ¥Chart.updateLayout was renamed to Chart._updateLayout

  • DatasetController.destroy 更名为 DatasetController._destroy

    ¥DatasetController.destroy was renamed to DatasetController._destroy

  • DatasetController.insertElements 更名为 DatasetController._insertElements

    ¥DatasetController.insertElements was renamed to DatasetController._insertElements

  • DatasetController.onDataPop 更名为 DatasetController._onDataPop

    ¥DatasetController.onDataPop was renamed to DatasetController._onDataPop

  • DatasetController.onDataPush 更名为 DatasetController._onDataPush

    ¥DatasetController.onDataPush was renamed to DatasetController._onDataPush

  • DatasetController.onDataShift 更名为 DatasetController._onDataShift

    ¥DatasetController.onDataShift was renamed to DatasetController._onDataShift

  • DatasetController.onDataSplice 更名为 DatasetController._onDataSplice

    ¥DatasetController.onDataSplice was renamed to DatasetController._onDataSplice

  • DatasetController.onDataUnshift 更名为 DatasetController._onDataUnshift

    ¥DatasetController.onDataUnshift was renamed to DatasetController._onDataUnshift

  • DatasetController.removeElements 更名为 DatasetController._removeElements

    ¥DatasetController.removeElements was renamed to DatasetController._removeElements

  • DatasetController.resyncElements 更名为 DatasetController._resyncElements

    ¥DatasetController.resyncElements was renamed to DatasetController._resyncElements

  • LayoutItem.isFullWidth 更名为 LayoutItem.isFullSize

    ¥LayoutItem.isFullWidth was renamed to LayoutItem.isFullSize

  • RadialLinearScale.setReductions 更名为 RadialLinearScale._setReductions

    ¥RadialLinearScale.setReductions was renamed to RadialLinearScale._setReductions

  • RadialLinearScale.pointLabels 更名为 RadialLinearScale._pointLabels

    ¥RadialLinearScale.pointLabels was renamed to RadialLinearScale._pointLabels

  • Scale.handleMargins 更名为 Scale._handleMargins

    ¥Scale.handleMargins was renamed to Scale._handleMargins

# 变化

¥Changed

本节中列出的 API 在签名或行为方面与版本 2 相比发生了变化。

¥The APIs listed in this section have changed in signature or behaviour from version 2.

# 缩放的变化

¥Changed in Scales

  • Scale.getLabelForIndexscale.getLabelForValue 取代

    ¥Scale.getLabelForIndex was replaced by scale.getLabelForValue

  • Scale.getPixelForValue 现在只需要一个参数。对于 TimeScale,该参数必须是自纪元以来的毫秒数。作为性能优化,它可能采用可选的第二个参数,给出数据点的索引。

    ¥Scale.getPixelForValue now only requires one parameter. For the TimeScale 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 callbacks

  • Scale.buildTicks 现在有望返回刻度对象

    ¥Scale.buildTicks is now expected to return tick objects

  • Scale.convertTicksToLabels 更名为 generateTickLabels。现在期望在作为输入给出的刻度上设置标签属性

    ¥Scale.convertTicksToLabels was renamed to generateTickLabels. It is now expected to set the label property on the ticks given as input

  • Scale.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 的第一个参数现在是包含 elementdatasetIndexindex 的对象数组

    ¥The first parameter to updateHoverStyle is now an array of objects containing the element, datasetIndex, and index

  • 签名或 resize 已更改,第一个 silent 参数已删除。

    ¥The signature or resize changed, the first silent parameter was removed.

# 数据集控制器

¥Dataset Controllers

  • updateElementupdateElements 取代,现在采用要更新的元素,start 索引、countmode

    ¥updateElement was replaced with updateElements now taking the elements to update, the start index, count, and mode

  • setHoverStyleremoveHoverStyle 现在额外占用 datasetIndexindex

    ¥setHoverStyle and removeHoverStyle now additionally take the datasetIndex and index

# 互动的变化

¥Changed in Interactions

  • 交互模式方法现在返回包含 elementdatasetIndexindex 的对象数组

    ¥Interaction mode methods now return an array of objects containing the element, datasetIndex, and index

# 布局的变化

¥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 的第二个参数现在是完整的选项对象,因此不再显式传递 stylerotationradius

    ¥The second parameter to drawPoint is now the full options object, so style, rotation, and radius are no longer passed explicitly

  • helpers.getMaximumHeighthelpers.dom.getMaximumSize 取代

    ¥helpers.getMaximumHeight was replaced by helpers.dom.getMaximumSize

  • helpers.getMaximumWidthhelpers.dom.getMaximumSize 取代

    ¥helpers.getMaximumWidth was replaced by helpers.dom.getMaximumSize

  • helpers.clear 已重命名为 helpers.clearCanvas,现在将 canvas 和可选的 ctx 作为参数。

    ¥helpers.clear was renamed to helpers.clearCanvas and now takes canvas and optionally ctx as parameter(s).

  • helpers.retinaScale 接受可选的第三个参数 forceStyle,它强制覆盖当前的画布样式。forceRatio 不再退回到 window.devicePixelRatio,而是默认为 1

    ¥helpers.retinaScale accepts optional third parameter forceStyle, which forces overriding current canvas style. forceRatio no longer falls back to window.devicePixelRatio, instead it defaults to 1.

# 平台的变化

¥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 是一个包含两个可用平台类 BasicPlatformDomPlatform 的对象。它还包含 BasePlatform,一个所有平台都必须扩展的类。

    ¥Chart.platforms is an object that contains two usable platform classes, BasicPlatform and DomPlatform. It also contains BasePlatform, a class that all platforms must extend from.

  • 如果传入的 canvas 是 OffscreenCanvas 的实例,则自动使用 BasicPlatform

    ¥If the canvas passed in is an instance of OffscreenCanvas, the BasicPlatform is automatically used.

  • isAttached 方法已添加到平台。

    ¥isAttached method was added to platform.

# IPlugin 接口的变化

¥Changed in IPlugin interface

  • 所有插件钩子都具有带有 3 个参数的统一签名:chartargsoptions。这意味着更改这些钩子的签名:beforeInitafterInitresetbeforeLayoutafterLayoutbeforeRenderafterRenderbeforeDrawafterDrawbeforeDatasetsDrawafterDatasetsDrawbeforeEventafterEventresizedestroy

    ¥All plugin hooks have unified signature with 3 arguments: chart, args and options. This means change in signature for these hooks: beforeInit, afterInit, reset, beforeLayout, afterLayout, beforeRender, afterRender, beforeDraw, afterDraw, beforeDatasetsDraw, afterDatasetsDraw, beforeEvent, afterEvent, resize, destroy.

  • afterDatasetsUpdateafterUpdatebeforeDatasetsUpdatebeforeUpdate 现在接收 args 对象作为第二个参数。options 参数始终是最后一个,因此从第 2 位移到了第 3 位。

    ¥afterDatasetsUpdate, afterUpdate, beforeDatasetsUpdate, and beforeUpdate now receive args object as second argument. options argument is always the last and thus was moved from 2nd to 3rd place.

  • afterEventbeforeEvent 现在接收一个封装的 event 作为第二个参数的 event 属性。原生事件可通过 args.event.native 获得。

    ¥afterEvent and beforeEvent now receive a wrapped event as the event property of the second argument. The native event is available via args.event.native.

  • 初始 resize 不再沉默。意味着 resize 事件可以在 beforeInitafterInit 之间触发

    ¥Initial resize is no longer silent. Meaning that resize event can fire between beforeInit and afterInit

  • 新钩子:installstartstopuninstall

    ¥New hooks: install, start, stop, and uninstall

  • afterEvent 应通过将 args.changed 设置为 true 来通知需要渲染的更改。因为 args 与所有插件共享,所以它应该只设置为 true 而不是 false。

    ¥afterEvent should notify about changes that need a render by setting args.changed to true. Because the args are shared with all plugins, it should only be set to true and not false.