有几种方法可以控制chart.js中尺度/图例之间的填充(文档中记录了一些官方方式和其他地方描述的某些“哈希”方式)。问题是,没有办法使用现有配置选项来控制整个图表中的填充(左侧比例,下侧比例,顶部比例或图例底部等)。
幸运的是,由于灵活的chart.js接口(并且因为我们可以创建新的缩放类型等),所以仍然可以控制填充而不用太多大惊小怪。让我解释一下添加左边,顶部和底部填充的方法,然后在末尾提供一个工作示例(如果您愿意,可以跳过)。
左填充
这一个是容易的。有一个记录的选项来控制这个。只需将scales.yAxes.ticks.padding
选项设置为您想要的值即可。这是一个例子。
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
padding: 25,
}
}]
}
的顶部填充(或传说填充)
没有选项来控制这个,所以我们必须建立它。我建立了它在创造新的传奇对象和覆盖afterFit()
功能使用在选项对象上设置的paddingBottom
选项。这不是太困难,但需要周围的方式来做到这一点。这是相关的代码。
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。
您好!谢谢,这是有效的。我非常震惊,对于这么小的事情需要太多的代码。我认为这个选项应该是默认包。非常感谢您的参与。 – Yuriy
我同意。如果我解决它,也许我会向chart.js家伙提交请求。 – jordanwillis