chart.jsのスケール/凡例間のパディングを制御する方法はいくつかあります(ドキュメントに記載されている正式な方法と、他の場所で説明されている「ハッキー」な方法)。問題は、既存の構成オプションを使用して、チャートの外にパディングを制御する方法(左のスケール、下のスケール、上のスケールまたは凡例の下など)がないことです。
幸運なことに、柔軟なchart.jsインターフェイス(新しいスケールタイプなどを作成することができるため)では、あまりにも面倒なことなく埋め込みを制御することができます。左、上、下の詰め物を追加して最後の最後に作業例を提供する方法を説明しましょう(あなたが望むなら、先に飛ばしてください)。
左パディング
この1つは簡単です。これを制御するための文書化されたオプションがあります。 scales.yAxes.ticks.padding
オプションを任意の値に設定するだけです。ここに例があります。
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
padding: 25,
}
}]
}
トップパディング(または伝説パディング)
これを制御するオプションは、我々はそれを構築する必要がありそうありません。私は新しいレジェンドオブジェクトを作成し、afterFit()
機能を上書きすることによって、それを内蔵optionsオブジェクトに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