ChartJS 图表无法调整大小

问题描述 投票:0回答:1

我正在创建一个带有两个 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;
}
javascript html css charts chart.js
1个回答
0
投票

在你的CSS样式中,需要将宽度和高度更改为max-widthmax-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>

演示代码

© www.soinside.com 2019 - 2024. All rights reserved.