最近新接了个web项目,用的是typscript,angular,oracle,protractor等技术。
再生成chart的时候引入了chart.js的类库。它实现的功能比较方便。
chartjs官网:https://www.chartjs.org/
下面介绍几种chartjs生成legend的方式:
方式1:options --> legend 属性,在这里可以指定labels是属性 来构建显示内容
var chart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
legend: {
display: true,
labels: {
fontColor: 'rgb(255, 99, 132)'
}
}
}
});
如果你要显示比较复杂的数据,有数据源的情况下, 可以使用以下属性
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. |
例子:
legend: {
labels: {
fontColor: VOLUME_BOA_CHART_HEX_COLOR.OFF_WHITE,
fontSize: 12,
padding: 32,
usePointStyle: true,
generateLabels: chart => chart.data.datasets.slice(0, 4).map((dataset, i) => ({ // chart.data.datasets是数据源
datasetIndex: i,
text: dataset.label.split(':')[0],
fillStyle: dataset.backgroundColor,
strokeStyle: dataset.borderColor,
lineDash: [5, 5],
pointStyle: legendIcon(i),
})),
},
position: 'bottom',
onClick: () => {},
},
方式2:关于复杂的legend(HTML),这个时候就不能用单纯的legend属性来设置了,需要用legendCallback
方法
仔细阅读了官方的文档是这样描述的:
Sometimes you need a very complex legend. In these cases, it makes sense to generate an HTML legend. Charts provide a generateLegend()
method on their prototype that returns an HTML string for the legend.
To configure how this legend is generated, you can change the legendCallback
config property.
Note that legendCallback is not called automatically and you must call generateLegend()
yourself in code when creating a legend