有几种方法可以控制 chart.js 中比例/图例之间的填充(文档中记录了一些官方方法和其他地方描述的一些“hacky”方法)。问题是,没有办法使用现有的配置选项来控制整个图表的填充(左比例、下比例、上比例......或图例的底部等)。
幸运的是,由于 chart.js 的灵活接口(并且因为我们可以创建新的比例类型等),仍然可以控制填充而不用大惊小怪。让我解释一下添加左侧、顶部和底部填充的方法,然后在最后提供一个工作示例(如果您愿意,请跳过)。
左填充
这个很简单。有一个记录在案的选项可以控制这一点。只需将scales.yAxes.ticks.padding 选项设置为您想要的任何值。这是一个例子。
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
padding: 25,
}
}]
}
顶部填充(或图例填充)
没有选项可以控制它,所以我们必须构建它。我通过创建一个新的 Legend 对象并覆盖使用选项对象上设置的 paddingBottom 选项的 afterFit() 函数来构建它。这不是太难,但需要绕道而行。这是相关代码。
function getBoxWidth(labelOpts, fontSize) {
return labelOpts.usePointStyle ?
fontSize * Math.SQRT2 :
labelOpts.boxWidth;
};
Chart.NewLegend = Chart.Legend.extend({
afterFit: function() {
this.height = this.height + this.options.paddingBottom;
},
});
function createNewLegendAndAttach(chartInstance, legendOpts) {
var legend = new Chart.NewLegend({
ctx: chartInstance.chart.ctx,
options: legendOpts,
chart: chartInstance
});
if (chartInstance.legend) {
Chart.layoutService.removeBox(chartInstance, chartInstance.legend);
delete chartInstance.newLegend;
}
chartInstance.newLegend = legend;
Chart.layoutService.addBox(chartInstance, legend);
}
// Register the legend plugin
Chart.plugins.register({
beforeInit: function(chartInstance) {
var legendOpts = chartInstance.options.legend;
if (legendOpts) {
createNewLegendAndAttach(chartInstance, legendOpts);
}
},
beforeUpdate: function(chartInstance) {
var legendOpts = chartInstance.options.legend;
if (legendOpts) {
legendOpts = Chart.helpers.configMerge(Chart.defaults.global.legend, legendOpts);
if (chartInstance.newLegend) {
chartInstance.newLegend.options = legendOpts;
} else {
createNewLegendAndAttach(chartInstance, legendOpts);
}
} else {
Chart.layoutService.removeBox(chartInstance, chartInstance.newLegend);
delete chartInstance.newLegend;
}
},
afterEvent: function(chartInstance, e) {
var legend = chartInstance.newLegend;
if (legend) {
legend.handleEvent(e);
}
}
});
底部填充
也没有选项来控制它,所以我们也必须内置它。由于我们在这里处理比例,所以最好的方法是扩展“类别”比例并添加逻辑来处理比例paddingTop 选项。通读源代码后,我们需要覆盖draw() 函数来执行此操作。这是相关代码(完整实现请参见我的示例)。
// ...
if (isHorizontal) {
if (options.position === 'bottom') {
// bottom
textBaseline = !isRotated? 'top':'middle';
textAlign = !isRotated? 'center': 'right';
labelY = me.top + tl + me.options.paddingTop;
} else {
// top
textBaseline = !isRotated? 'bottom':'middle';
textAlign = !isRotated? 'center': 'left';
labelY = me.bottom - tl;
}
}
// ...
这是一个codepen example,展示了所有这些。