如何最小化ChartJS动态加载的极区图的大小



我使用的是ChartJS的极区图。我正在动态加载图表。

const chartData = [
[10, 20, 30],
[20, 30, 40],
[30, 40, 50]
];
// Loop through the chart data and create a chart for each
for (let i = 0; i < chartData.length; i++) {
debugger;
// Create a canvas element with a unique ID
const canvas = document.createElement('canvas');
canvas.id = `chart-${i}`;
canvas.style.width = '100px';
canvas.style.height = '100px';
// Add the canvas to the page
const chartContainer = document.getElementById('chart-containerpolar');
chartContainer.appendChild(canvas);
// Create a new Chart object for the canvas
const chart = new Chart(canvas, {
type: 'polarArea',
data: {
datasets: [{
data: chartData[i],
backgroundColor: [
"rgb(68, 114, 197)",
"rgb(255, 191, 0)",
"rgb(104, 163, 68)"
//'rgba(75, 192, 192, 0.2)',
//'rgba(153, 102, 255, 0.2)',
//'rgba(255, 159, 64, 0.2)'
],
}],
labels: ['Part1', 'Part2', 'Part3']
},
options: {
responsive: true,
/* maintainAspectRatio: false,*/
scale: {
ticks: {
beginAtZero: true
}
}
}
});
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="chart-containerpolar"></div>

如何减小画布宽度= 100px"身高="100 px"。我尝试了所有方法,但图表加载了默认值。我试过maintainAspectRatio: false但之后图表就消失了。

CharJS调整/渲染画布相对于它的父容器。所以如果你想减小画布的大小那么你只需要减小它的容器的大小。

有关更多信息,请查看响应性文档指南

下面是修改后的代码(修改只在.html文件中)

const chartData = [
[10, 20, 30],
[20, 30, 40],
[30, 40, 50]
];
// Loop through the chart data and create a chart for each
for (let i = 0; i < chartData.length; i++) {
debugger;
// Create a canvas element with a unique ID
const canvas = document.createElement('canvas');
canvas.id = `chart-${i}`;
canvas.style.width = '100px';
canvas.style.height = '100px';
// Add the canvas to the page
const chartContainer = document.getElementById('chart-containerpolar');
chartContainer.appendChild(canvas);
// Create a new Chart object for the canvas
const chart = new Chart(canvas, {
type: 'polarArea',
data: {
datasets: [{
data: chartData[i],
backgroundColor: [
"rgb(68, 114, 197)",
"rgb(255, 191, 0)",
"rgb(104, 163, 68)"
//'rgba(75, 192, 192, 0.2)',
//'rgba(153, 102, 255, 0.2)',
//'rgba(255, 159, 64, 0.2)'
],
}],
labels: ['Part1', 'Part2', 'Part3']
},
options: {
responsive: true,
/* maintainAspectRatio: false,*/
scale: {
ticks: {
beginAtZero: true
}
}
}
});
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div id="chart-containerpolar" style="width: 300px; height: 300px"></div>
<!-- You need to make sure that container has the proper size and width so that chart canvas can take the size relatively to it's parent -->