ChartJS图表不调整大小

bgibtngc  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(149)

我正在创建一个带有两个x轴和一个y轴的图表的程序,但我想让图表更小。
当我试着“宽度:50px”和“高度:50px”,它没有调整大小。我还添加了响应:但这并不管用有什么解决办法吗?
当前代码:
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;

超文本标记语言:
<canvas id="chart"></canvas>
CSS:

#chart {
    background: black;
    padding: 20px;
    border-radius: 30px;
    margin-bottom: 50px;
    width: 20px;
    height: 20px;
}
6bc51xsx

6bc51xsx1#

在你的css样式中,需要将width和height改为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>

democode

相关问题