有幾種方法可以控制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