c3-adaptor
config.js
js
const CHART_OPTION = {
HEIGHT: 380,
PADDING_TOP: 50,
COLOR_PATTERN: [
'#45454d',
'#ce2e6c',
'#f75f00',
'#43ab92',
'#512c62',
'#504658',
'#1089ff'
],
POINT_RADIUS: 4
}
const COMMON_CHART_OPTION = {
padding: {
top: CHART_OPTION.PADDING_TOP
},
size: {
height: CHART_OPTION.HEIGHT
},
color: {
pattern: CHART_OPTION.COLOR_PATTERN
},
point: {
r: CHART_OPTION.POINT_RADIUS
},
legend: {
position: 'inset',
inset: {
anchor: 'top-right',
y: -CHART_OPTION.PADDING_TOP,
step: 1
}
},
grid: {
y: {
show: true
}
}
}
chart-adaptor.js
js
const LABEL_NAME = 'x'
const AXIS_X_TYPE = 'timeseries'
const mountChart = (options) => {
const {
element,
labels,
columns,
xAxisFormat,
tooltipTitleFormat,
tooltipValueFormat
} = options
const chart = c3.generate(Object.assign({
bindto: element,
data: {
x: LABEL_NAME,
columns: [
[
LABEL_NAME,
...labels
],
...columns
],
},
axis: {
x: {
type: AXIS_X_TYPE,
tick: {
format: xAxisFormat
}
}
},
tooltip: {
format: {
title: tooltipTitleFormat,
value: tooltipValueFormat,
}
}
}, COMMON_CHART_OPTION));
return chart
}
const changeData = (options) => {
const {
chart,
labels,
columns
} = options
chart.load({
columns: [
[
LABEL_NAME,
...labels
],
...columns
],
})
return chart
}
scripts.js
js
window.onload = () => {
const element = document.querySelector('#chart-date')
const labels = [
'2010-01-01',
'2011-01-01',
'2012-01-01',
'2013-01-01',
'2014-01-01',
'2015-01-01',
'2016-01-01',
'2017-01-01'
]
const columns = Array
.from({length: 10}, (v, index) => index + 1)
.map(index => {
return [`data${index}`]
.concat([110, 90, 110, 90, 110, 90, 110, 90].map(v => v * index))
})
const chart = mountChart({
element,
labels,
columns,
xAxisFormat: (x) => {
return x.getFullYear()
},
tooltipTitleFormat: (x) => {
const year = x.getFullYear()
const month = x.getMonth() + 1
return `${year}.${month > 10 ? month : '0' + month}`
},
tooltipValueFormat: value => `${value}%`,
})
setTimeout(() => {
const copiedLabels = [...labels]
const copiedColumns = [...columns]
copiedColumns.forEach(items => {
items.length = items.length - 1
})
copiedLabels.length = copiedLabels.length - 1
changeData({
chart,
labels: copiedLabels,
columns: copiedColumns,
})
}, 5000)
}