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

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

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 } }] } } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <div class="graph"> <div class="chart-legend"> </div> <div class="chart"> <canvas id="myChart"></canvas> </div> </div>

参见关于小提琴的代码:Jsfiddle


当前回答

最简单的方法是为画布创建一个容器,并设置它的高度:

<div style="height: 300px">
  <canvas id="chart"></canvas>
</div>

并设置

options: {  
    responsive: true,
    maintainAspectRatio: false
}

其他回答

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

我在代码中是这样做的:

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

看,在初始化语句中有一个错误。maintainAspectRatio应该放在选项对象中,如下所示

...

options = {
   maintainAspectRatio: false,

 ...
}

...

现在,你可以做的是设置图表父元素的高度,这里div .chart是div #myChart的父元素。 因此,指定div .chart的高度就可以了。

考虑下面的代码。

<div class="chart" style="height: 500px;">
   <canvas id="myChart"></canvas>
</div>

根据你自己改变高度,对我来说,500px就可以了;)

他是对的。如果你想继续使用jQuery,你可以这样做

var ctx = $('#myChart')[0];
ctx.height = 500;

or

var ctx = $('#myChart');
ctx.attr('height',500);

设置chartjs图表的大小可以简单地通过设置周围容器的with来实现:

   <div style="width:400px;">
     <canvas id="myChart"></canvas>
   </div>

但是一个重要的细节是,你可能需要在创建之后调整图表的大小:

var ctx = $('#myChart');
var myChart = new Chart(ctx, {
    ......
    data: {
           ........
    },
    options: {
        responsive: false,
        maintainAspectRatio: true
    }
});
// now resize the new chart to fit into the canvas....
myChart.resize();

如果你在选项中禁用了保持纵横比,那么它将使用可用的高度:

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