我想知道如果图例中的项目数量不适合其初始大小,是否有办法使图表的宽度增加
我尝试了很多不同的设置和方法,例如更改容器上的样式属性,但没有一个可以解决我的问题。
我使用Chart.js v3.8.1 我准备了一个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);
}
您可以按照以下步骤动态调整宽度:
// Set the number of data points
const numData = 60;
let preparedData = prepareData(numData);
// Calculate the extra width based on the number of data points
// In this example, we add 15px for each additional data point
const extraWidthPerItem = 15;
const extraWidth = numData * extraWidthPerItem;
// Set the base width of the canvas
const baseWidth = 400;
// Calculate the total width by adding the extra width to the base width
const totalWidth = baseWidth + extraWidth;
// Apply the total width to the canvas element
const canvas = $("canvas");
canvas.attr("width", totalWidth);