Chart.js ignoring canvas height & width

安稳与你 提交于 2019-12-23 07:34:37

问题


Following the Chart.js documentation I am trying to draw a small chart:

<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels:['15-2016','16-2016','17-2016',],
    datasets:[
      {
        label:'Yes',
        data:[3.4884,1.1628,1.3514,],
        backgroundColor:'rgba(75,192,192,1)',
        borderColor:'rgba(75,192,192,1)',
        pointRadius:0
      },
      {
        label:'Maybe',
        data:[0.5571,1.3298,0.791,],
        backgroundColor:'rgba(255,206,86,1)',
        borderColor:'rgba(255,206,86,1)',
        pointRadius:0
      },
      {
        label:'No',
        data:[0,0,0,],
        backgroundColor:'rgba(255,99,132,1)',
        borderColor:'rgba(255,99,132,1)',
        pointRadius:0
      }
    ]
  }        
});
</script>

However, when the page is rendered the canvas somehow becomes

<canvas style="height: 929px; width: 929px;" id="myChart" width="1858" height="1858"></canvas>

which is waaaaay too big for my needs. How can I set the width and height of the canvas to be what I want?


回答1:


I was able to hardcode the size of the graph by turning off responsiveness:

options: {
  responsive: false
}



回答2:


I solved the problem by adding "maintainAspectRatio: false" to the options.

options : {
    maintainAspectRatio: false
};



回答3:


Using Both options, maintainAspectRatio: false AND responsive: false seem to do the trick of making the chart fit the canvas as sized in the canvas height and width tags.



来源:https://stackoverflow.com/questions/37577892/chart-js-ignoring-canvas-height-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!