提问者:小点点

在chart.js中设置图表高度


我想用chart.js绘制一个水平条形图,但它一直在缩放图表,而不是使用我在脚本中为画布分配的高度。

有没有办法从脚本中设置图形的高度?

参见fiddle:Jsfidle

HTML

<div class="graph">
  <div class="chart-legend">

  </div>
  <div class="chart">
    <canvas id="myChart"></canvas>
  </div>
</div>

JavaScript

var ctx = $('#myChart');

ctx.height(500);

var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    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
        }]
    },
    maintainAspectRatio: false,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

共2个答案

匿名用户

似乎var ctx=$('#MyChart');返回的是元素列表。您需要使用ctx[0]引用第一个。而且高度是一个属性,而不是一个函数。

我在代码中是这样做的:

var ctx = document.getElementById("myChart");
ctx.height = 500;

匿名用户

如果在选项中禁用“保持纵横比”,则它将使用可用高度:

var chart = new Chart('blabla', {
                type: 'bar',
                data: {
                },
                options: {
                    maintainAspectRatio: false,
                }
            });