我正在创建一个带有两个 x 轴和一个 y 轴图表的程序,但我想让图表更小。
当我尝试“宽度:50px”和“高度:50px”时,它没有调整大小。我还在图表的设置中添加了responsive: true,但这不起作用。有什么办法解决这个问题吗?
当前代码:
JS:
const data = {
//labels: ['Younger Than 18', '18-30', '31-45', 'Older than 45', 'Unknown'],
datasets: [{
label: 'Races/Ethnicities',
data: [
20, 30, 30, 40, 50
],
backgroundColor: 'rgba(255, 26, 104, 0.2)',
borderColor: 'rgba(255, 26, 104, 1)',
tension: 0.4,
yAxisID: 'y'
},
{
label: 'Ages',
data: [
10, 20, 30, 40, 50
],
backgroundColor: 'rgba(0, 26, 104, 0.2)',
borderColor: 'rgba(0, 26, 104, 1)',
tension: 0.4,
}]
};
// config
const config = {
maintainAspectRatio: false,
responsive: true,
type: 'line',
data,
options: {
scales: {
y: {
beginAtZero: true,
type: 'linear',
position: 'left'
},
x1: {
labels: ['White (Non-Hispanic)', 'Black (Non-Hispanic)', 'Hispanic (Black Or White)', 'Asian', 'Unknown'],
},
x2: {
position: 'top',
labels: ['Younger than 18', '18-30', '31-45', 'Older than 45', 'Unknown'],
},
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('chart'),
config
);
// Instantly assign Chart.js version
const chartVersion = document.getElementById('chartVersion');
chartVersion.innerText = Chart.version;
HTML:
<canvas id="chart"></canvas>
CSS:
#chart {
background: black;
padding: 20px;
border-radius: 30px;
margin-bottom: 50px;
width: 20px;
height: 20px;
}
在你的CSS样式中,需要将宽度和高度更改为max-width和max-height。
我自己尝试了这个代码,没问题。
#chart {
background: black;
padding: 20px;
border-radius: 30px;
margin-bottom: 50px;
max-width: 1000px;//change here to resize
max-height: 500px;
}
我使用以下js代码
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js'></script>