charts.js图表 大小,它与容器设置的大小不同

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

[我使用250x250画布元素来显示由Charts.js生成的字符,但所设置的字符比我设置的大,我是否错过了一些配置?此代码主要是官方文档的示例,但我不能设置大小。

<div class="row">
        <div class="card chart-card">
            <div class="card-header">
                Estadísticas
            </div>
            <div class="card-body">
                <canvas id="myChart" width="250px" height="250px"></canvas>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>   
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>   
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
</script>
html css chart.js
2个回答
0
投票

尝试向选项对象添加2个属性:

responsive: true,
maintainAspectRatio: false

0
投票
options: {
    maintainAspectRatio: false,
    responsive: true,
    scales: {
        yAxes: [{
           ticks: {
             beginAtZero: true
            }
        }]
   }
}

这将解决您的问题。但是它将固定高度。对于宽度,我认为您必须像这样定义canvas元素父级的宽度。

<div class="chart">
  <canvas id="myChart" height="250px"></canvas>
</div>
.chart {
  width: 250px;
}

请参见此处获取文档。https://www.chartjs.org/docs/latest/general/responsive.html

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