I would like to know if there is a way to make the chart’s width increase if the number of items in the legend doesn’t fit with its initial size
I tried a lot of different settings and approces like changing style attributes on container but none of them could solve my problem.
I use Chart.js v3.8.1
I prepared a codepen to help me explain the request:
Codepen
<div class="container">
<div class="chart-container">
<canvas style="height: 300px; width: 100%"></canvas>
</div>
</div>
.container {
width: 100%;
height: 400px;
border: 3px solid red;
display: flex;
}
.chart-container {
border: 2px solid blue;
width: fit-content;
margin: auto 0;
width: fit-content;
}
canvas {
border: 2px solid green;
}
$(document).ready(() => {
let preparedData = prepareData(60);
const config = {
type: "doughnut",
data: preparedData,
options: {
responsive: false,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: "right"
}
}
}
};
let chart = new Chart($("canvas"), config);
});
function prepareData(numData) {
let labels = [];
let localData = [];
for (idx = 0; idx < numData; idx++) {
labels.push("Data " + idx);
let random = getRandomInt(100);
localData.push(random);
}
let datasets = [
{
label: "Info",
data: localData,
borderWidth: 0
}
];
return { labels, datasets };
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}