Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js ignoring canvas height & width

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?

like image 766
wogsland Avatar asked Jun 01 '16 20:06

wogsland


People also ask

How do I set the size of a Chartjs?

To set the chart size in ChartJS, we recommend using the responsive option, which makes the Chart fill its container. You must wrap the chart canvas tag in a div in order for responsive to take effect. You cannot set the canvas element size directly with responsive .

Is chart js responsive?

Luckily, Chart. js does most of this complex work for us! A Chart. js chart is responsive by default, but with one limitation: it maintains its aspect ratio.

Does chart js use canvas?

Chart. js charts are rendered on user provided canvas elements. Thus, it is up to the user to create the canvas element in a way that is accessible. The canvas element has support in all browsers and will render on screen but the canvas content will not be accessible to screen readers.


2 Answers

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

options: {
  responsive: false
}
like image 119
wogsland Avatar answered Sep 24 '22 03:09

wogsland


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

options : {
    maintainAspectRatio: false
};
like image 42
Patrick Dorn Avatar answered Sep 22 '22 03:09

Patrick Dorn