[chart.js] Setting width and height

I'm trying out the example code for Chart.js given in the docs.

Width and height is specified inline on the canvas element at 400px/400px.

But when rendering the chart it's blown up to full page width, and cuts off the far right end.

See example

How/where am I supposed to control the width/height of the chart?

This is some bogus text because SO prohibits linking to Codepen otherwise.

This question is related to chart.js

The answer is


Works for me too

responsive:true
maintainAspectRatio: false


<div class="row">
        <div class="col-xs-12">
            <canvas id="mycanvas" width="500" height="300"></canvas>
        </div>
    </div>

Thank You


Use this, it works fine.

<canvas id="totalschart" style="height:400px;width: content-box;"></canvas>

and under options,

responsive:true,

This helped in my case:

options: {
    responsive: true,
    scales: {
        yAxes: [{
            display: true,
            ticks: {
                min:0,
                max:100
            }
        }]
    }
}

In my case, passing responsive: false under options solved the problem. I'm not sure why everybody is telling you to do the opposite, especially since true is the default.


You can also simply surround the chart with container (according to official doc http://www.chartjs.org/docs/latest/general/responsive.html#important-note)

<div class="chart-container">
    <canvas id="myCanvas"></canvas>
</div>

CSS

.chart-container {
    width: 1000px;
    height:600px
}

and with options

responsive:true
maintainAspectRatio: false

I cannot believe nobody talked about using a relative parent element.

Code:

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="chart"></canvas>
</div>

Sources: Official documentation


Not mentioned above but using max-width or max-height on the canvas element is also a possibility.


The below worked for me - but dont forget to put this in the "options" param.

var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
    maintainAspectRatio: false,
    responsive:true,
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}
});

You can change the aspectRatio according to your needs:

options:{
     aspectRatio:4 //(width/height)
}