翻译于:2016年11月8日 09:42:06
Chart.js 提供许多创建图表的参数,可以通过传递不同参数值来创建不同的图表。或者,通过改变全局配置文件来调整。
图表数据
创建图表的时候,需要把创建图表所需的所有数据放入一个数据对象中,然后向图表传递这个对象,这个数据对象可以包含下面这些参数
参数名 | 类型 | 描述 |
datasets | Array[object] | 包含有一组数据的数据组。 查阅文档来确定有哪些可用参数是可添加到数据组中的。 |
labels | Array[string] | 跟 category axis 一起使用的可选参数。 |
xLabels | Array[string] | 横向坐标轴 类别 |
yLabels | Array[string] | 纵向坐标轴 类别 |
绘制带参数创建图表
绘制一个带参数的图表,只需要向图表创建方法传递一个包含所需参数的对象即可。在下面这个例子中,设置了图表是不响应的。
var chartInstance = new Chart(ctx, {
type: 'line',
data: data,
options: {
responsive: false
}
});
全局配置
全局配置这个概念在 Chart.js 1.0 中已经介绍了,全局配置文件可以方便的改变所有的图表样式,或者个性化其中的某一个图表。
Chart.js merges the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in Chart.defaults.global
. The defaults for each chart type are discussed in the documentation for that chart type.
The following example would set the hover mode to ‘single’ for all charts where this was not overridden by the chart type defaults or the options passed to the constructor on creation.
Chart.defaults.global.hover.mode = 'single';
// Hover mode is set to single because it was not overridden here
var chartInstanceHoverModeSingle = new Chart(ctx, {
type: 'line',
data: data,
});
// This chart would have the hover mode that was passed in
var chartInstanceDifferentHoverMode = new Chart(ctx, {
type: 'line',
data: data,
options: {
hover: {
// Overrides the global setting
mode: 'label'
}
}
})
全局字体设置
有4个可以改变全局图表字体样式的参数,这些参数在全局配置文件 Chart.defaults.global
中
名称 | 类型 | 默认 | 描述 |
defaultFontColor | Color | ‘#666’ | 默认字体颜色 |
defaultFontFamily | String | “‘Helvetica Neue’, ‘Helvetica’, ‘Arial’, sans-serif” | 默认字体 |
defaultFontSize | Number | 12 | 默认字体大小(单位:px),Does not apply to radialLinear scale point labels |
defaultFontStyle | String | ‘normal’ | 默认字体样式。不会应用于提示弹窗的字体。不会应用于图表标题 |
通用图表配置
下面的设置选项适用于所有的图表, 你可以在全局配置文件中设置 global configuration,也可以在构建图表的时候传递给构建方法。
名称 | 类型 | 默认 | 描述 |
responsive | Boolean | true | 在图表容器canvas变化的时候自适应 |
responsiveAnimationDuration | Number | 0 | 图表自适应新尺寸所用时间 |
maintainAspectRatio | Boolean | true | 调整大小时保持横纵比 |
events | Array[String] | [“mousemove”, ”mouseout”, ”click”, ”touchstart”, ”touchmove”, ”touchend”] | 弹出提示小窗口要监听的事件 |
onClick | Function | null | Called if the event is of type ‘mouseup’ or ‘click’. Called in the context of the chart and passed an array of active elements |
legendCallback | Function | | Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string. |
onResize | Function | null | Called when a resize occurs. Gets passed two arguemnts: the chart instance and the new size. |
标题配置选项
标题相关配置设置在 options -> title
域中,相关的全局配置在 Chart.defaults.global.title
中。
名称 | 类型 | 默认 | 描述 |
display | Boolean | false | 是否显示标题 |
position | String | ‘top’ | 指定标题的位置。 可用参数有’top’, ‘left’, ‘bottom’ 和’right’ |
fullWidth | Boolean | true | Marks that this box should take the full width of the canvas (pushing down other boxes) |
fontSize | Number | 12 | 文字大小,默认继承全局配置中的设定值 |
fontFamily | String | “‘Helvetica Neue’, ‘Helvetica’, ‘Arial’, sans-serif” | 文字字体,默认继承全局配置中的设定值 |
fontColor | Color | “#666” | 文字颜色,默认继承全局配置中的设定值 |
fontStyle | String | ‘bold’ | 文字样式,默认继承全局配置中的设定值 |
padding | Number | 10 | 在标题上下添加的间隔(单位为px) |
text | String | ” | 标题内容 |
示例
下面的例子会在创建图表的时候会包含标题“自定义图表标题”
var chartInstance = new Chart(ctx, {
type: 'line',
data: data, //data这里代表的是数值数组
options: {
title: {
display: true,
text: '自定义图表标题'
}
}
})
图例
图例相关的配置在options -> legend
域中,相关全局配置在Chart.defaults.global.legend
中。
名称 | 类型 | 默认 | 描述 |
display | Boolean | true | 是否显示图例 |
position | String | ‘top’ | 图例位置。可用的位置有上下左右,’top’, ‘left’, ‘bottom’ and ‘right’. |
fullWidth | Boolean | true | Marks that this box should take the full width of the canvas (pushing down other boxes) |
onClick | Function | | A callback that is called when a click is registered on top of a label item |
labels | Object | - | 参阅下面的 图例文字选项. |
图例文字选项
图例文字选项写在图例选项下面的options -> legend -> lables
中。
名称 | 类型 | 默认 | 描述 |
boxWidth | Number | 40 | Width of coloured box |
fontSize | Number | 12 | 文字大小,默认继承全局配置中的设定值 |
fontStyle | String | “normal” | 文字样式,默认继承全局配置中的设定值 |
fontColor | Color | “#666” | 文字颜色,默认继承全局配置中的设定值 |
fontFamily | String | “‘Helvetica Neue’, ‘Helvetica’, ‘Arial’, sans-serif” | 文字字体,默认继承全局配置中的设定值 |
padding | Number | 10 | 同行图例之间的 Padding |
generateLabels: | Function | | Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See Legend Item for details. |
usePointStyle | Boolean | false | Label style will match corresponding point style (size is based on fontSize, boxWidth is not used in this case). |
图例接口
Items passed to the legend onClick
function are the ones returned from labels.generateLabels
. These items must implement the following interface.
{
// 文字
text: String,
// 图例方块颜色
fillStyle: Color,
// If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect
hidden: Boolean,
// For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap
lineCap: String,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
lineDash: Array[Number],
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
lineDashOffset: Number,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
lineJoin: String,
// Width of box border
lineWidth: Number,
// Stroke style of the legend box
strokeStyle: Color
// Point style of the legend box (only used if usePointStyle is true)
pointStyle: String
}
示例
下面的例子将创建一个带图例的图表,图例文字颜色设置为红色。
var chartInstance = new Chart(ctx, {
type: 'bar',
data: data, //data 数据数组
options: {
legend: { //图例相关配置
display: true,
labels: { //图例文字
fontColor: 'rgb(255, 99, 132)'
}
}
}
});
提示弹窗 - 配置选项
tooltip相关配置在 options -> tooltips
中,相关的全局配置在 Chart.defaults.global.tooltips
中。
名称 | 类型 | 默认值 | 描述 |
enabled | Boolean | true | 是否开启 |
custom | Function | null | 参阅下面的 section 部分 |
mode | String | ‘single’ | 设置哪个元素要显示在提示弹窗中,可用的参数有 |
itemSort | Function | undefined | Allows sorting of tooltip items. Must implement a function that can be passed to Array.prototype.sort |
backgroundColor | Color | ‘rgba(0,0,0,0.8)’ | 背景颜色 |
titleFontFamily | String | “‘Helvetica Neue’, ‘Helvetica’, ‘Arial’, sans-serif” | 标题文字字体,默认继承全局配置中的设置 |
titleFontSize | Number | 12 | 标题字体大小,默认继承全局配置中的设置 |
titleFontStyle | String | “bold” | 标题字体样式,默认继承全局配置中的设置 |
titleFontColor | Color | “#fff” | 标题字体颜色,默认继承全局配置中的设置 |
titleSpacing | Number | 2 | 标题上下的padding |
titleMarginBottom | Number | 6 | 标题下方的margin |
bodyFontFamily | String | “‘Helvetica Neue’, ‘Helvetica’, ‘Arial’, sans-serif” | 内容字体,默认继承全局配置中的设置 |
bodyFontSize | Number | 12 | 内容字体大小,默认继承全局配置中的设置 |
bodyFontStyle | String | “normal” | 内容字体样式,默认继承全局配置中的设置 |
bodyFontColor | Color | “#fff” | 内容字体颜色,默认继承全局配置中的设置 |
bodySpacing | Number | 2 | 内容上下的padding |
footerFontFamily | String | “‘Helvetica Neue’, ‘Helvetica’, ‘Arial’, sans-serif” | footer字体,默认继承全局配置中的设置 |
footerFontSize | Number | 12 | footer字体大小,默认继承全局配置中的设置 |
footerFontStyle | String | “bold” | footer字体样式 |
footerFontColor | Color | “#fff” | footer字体颜色 |
footerSpacing | Number | 2 | footer上下的padding |
footerMarginTop | Number | 6 | footer上面的margin |
xPadding | Number | 6 | 左右的padding |
yPadding | Number | 6 | 上下的padding |
caretSize | Number | 5 | 对话框引出箭头大小,单位px |
cornerRadius | Number | 6 | 圆角大小 |
multiKeyBackground | Color | “#fff” | Color to draw behind the colored boxes when multiple items are in the tooltip |
callbacks | Object | See the callbacks section below |
Tooltip 回调
The tooltip label configuration is nested below the tooltip configuration using the callbacks
key. The tooltip has the following callbacks for providing text. For all functions, ‘this’ will be the tooltip object created from the Chart.Tooltip constructor.
All functions are called with the same arguments: a tooltip item and the data object passed to the chart. All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text.
Callback | Arguments | Description |
beforeTitle | | Text to render before the title |
title | | Text to render as the title |
afterTitle | | Text to render after the title |
beforeBody | | Text to render before the body section |
beforeLabel | | Text to render before an individual label |
label | | Text to render for an individual item in the tooltip |
labelColor | | Returns the colors to render for the tooltip item. Return as an object containing two parameters: |
afterLabel | | Text to render after an individual label |
afterBody | | Text to render after the body section |
beforeFooter | | Text to render before the footer section |
footer | | Text to render as the footer |
afterFooter | | Text to render after the footer section |
Tooltip Item Interface
The tooltip items passed to the tooltip callbacks implement the following interface.
{
// X Value of the tooltip as a string
xLabel: String,
// Y value of the tooltip as a string
yLabel: String,
// Index of the dataset the item comes from
datasetIndex: Number,
// Index of this data item in the dataset
index: Number
}
悬停 - 配置选项
The hover configuration is passed into the options.hover
namespace. The global hover configuration is at Chart.defaults.global.hover
.
Name | Type | Default | Description |
mode | String | ‘single’ | Sets which elements hover. Acceptable options are |
animationDuration | Number | 400 | Duration in milliseconds it takes to animate hover style changes |
onHover | Function | null | Called when any of the events fire. Called in the context of the chart and passed an array of active elements (bars, points, etc) |
动画 - 配置选项
The following animation options are available. The global options for are defined in Chart.defaults.global.animation
.
Name | Type | Default | Description |
duration | Number | 1000 | The number of milliseconds an animation takes. |
easing | String | “easeOutQuart” | Easing function to use. |
onProgress | Function | none | Callback called on each step of an animation. Passed a single argument, an object, containing the chart instance and an object with details of the animation. |
onComplete | Function | none | Callback called at the end of an animation. Passed the same arguments as |
动画回调
The onProgress
and onComplete
callbacks are useful for synchronizing an external draw to the chart animation. The callback is passed an object that implements the following interface. An example usage of these callbacks can be found on Github. This sample displays a progress bar showing how far along the animation is.
{
// Chart object
chartInstance,
// Contains details of the on-going animation
animationObject,
}
Animation Object
The animation object passed to the callbacks is of type Chart.Animation
. The object has the following parameters.
{
// Current Animation frame number
currentStep: Number,
// Number of animation frames
numSteps: Number,
// Animation easing to use
easing: String,
// Function that renders the chart
render: Function,
// User callback
onAnimationProgress: Function,
// User callback
onAnimationComplete: Function
}
Element Configuration
The global options for elements are defined in Chart.defaults.global.elements
.
Options can be configured for four different types of elements; arc, lines, points, and rectangles. When set, these options apply to all objects of that type unless specifically overridden by the configuration attached to a dataset.
Arc Configuration
Arcs are used in the polar area, doughnut and pie charts. They can be configured with the following options. The global arc options are stored in Chart.defaults.global.elements.arc
.
Name | Type | Default | Description |
backgroundColor | Color | ‘rgba(0,0,0,0.1)’ | Default fill color for arcs. Inherited from the global default |
borderColor | Color | ‘#fff’ | Default stroke color for arcs |
borderWidth | Number | 2 | Default stroke width for arcs |
曲线图表选项
Line elements are used to represent the line in a line chart. The global line options are stored in Chart.defaults.global.elements.line
.
Name | Type | Default | Description |
tension | Number | 0.4 | Default bezier curve tension. Set to |
backgroundColor | Color | ‘rgba(0,0,0,0.1)’ | Default line fill color |
borderWidth | Number | 3 | Default line stroke width |
borderColor | Color | ‘rgba(0,0,0,0.1)’ | Default line stroke color |
borderCapStyle | String | ‘butt’ | Default line cap style. See MDN |
borderDash | Array | | Default line dash. See MDN |
borderDashOffset | Number | 0.0 | Default line dash offset. See MDN |
borderJoinStyle | String | ‘miter’ | Default line join style. See MDN |
capBezierPoints | Boolean | true | If true, bezier control points are kept inside the chart. If false, no restriction is enforced. |
fill | Boolean | true | If true, the line is filled. |
stepped | Boolean | false | If true, the line is shown as a stepped line and ‘tension’ will be ignored |
Point Configuration
Point elements are used to represent the points in a line chart or a bubble chart. The global point options are stored in Chart.defaults.global.elements.point
.
Name | Type | Default | Description |
radius | Number | 3 | Default point radius |
pointStyle | String | ‘circle’ | Default point style |
backgroundColor | Color | ‘rgba(0,0,0,0.1)’ | Default point fill color |
borderWidth | Number | 1 | Default point stroke width |
borderColor | Color | ‘rgba(0,0,0,0.1)’ | Default point stroke color |
hitRadius | Number | 1 | Extra radius added to point radius for hit detection |
hoverRadius | Number | 4 | Default point radius when hovered |
hoverBorderWidth | Number | 1 | Default stroke width when hovered |
Rectangle Configuration
Rectangle elements are used to represent the bars in a bar chart. The global rectangle options are stored in Chart.defaults.global.elements.rectangle
.
Name | Type | Default | Description |
backgroundColor | Color | ‘rgba(0,0,0,0.1)’ | Default bar fill color |
borderWidth | Number | 0 | Default bar stroke width |
borderColor | Color | ‘rgba(0,0,0,0.1)’ | Default bar stroke color |
borderSkipped | String | ‘bottom’ | Default skipped (excluded) border for rectangle. Can be one of |
颜色
When supplying colors to Chart options, you can use a number of formats. You can specify the color as a string in hexadecimal, RGB, or HSL notations. If a color is needed, but not specified, Chart.js will use the global default color. This color is stored at Chart.defaults.global.defaultColor
. It is initially set to ‘rgba(0, 0, 0, 0.1)’;
You can also pass a CanvasGradient object. You will need to create this before passing to the chart, but using it you can achieve some interesting effects.
The final option is to pass a CanvasPattern object. For example, if you wanted to fill a dataset with a pattern from an image you could do the following.
var img = new Image();
img.src = 'https://example.com/my_image.png';
img.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
var fillPattern = ctx.createPattern(img, 'repeat');
var chart = new Chart(ctx, {
data: {
labels: ['Item 1', 'Item 2', 'Item 3'],
datasets: [{
data: [10, 20, 30],
backgroundColor: fillPattern
}]
}
})
}