53๐
I also needed a responsive canvas and had this issue. This was my fix:
<div>
<canvas id="chart"></canvas>
</div>
Since Chart.js scales the canvas to the width of the container, ignoring the padding, I just wrapped the canvas in a div
. The div
scales to the container with padding, respecting the padding, and then the responsive Chart.js canvas
scales to the div
.
4๐
I too googled for this problem and ended up with a simple solution.
I added height
so that it automatically adjust the width accordingly and show it in a nicer way. If u really want you could add width
too. The canvas
element is part of HTML5
.
It does not allow you to input values with px
. So ignore that and just type tha numerical value u need.
<canvas id="myChart" height="80"></canvas>
3๐
In your jsfiddle example change the responsive
attribute to false:
var options = {
maintainAspectRatio: true,
responsive: false
};
The previous setting added a additional 30px to both the height and width when you inspect the element using Chrome dev tools. Because of the size of the canvas it should not be problematic when it comes to resizing of the canvas.
3๐
A better solution is to use
.container {box-sizing: border-box;}
0๐
I wrapped the in and then used this CSS.
.chart-container {
box-sizing:border-box;
margin:2%;
width:96%;
}
This keeps it padded from the edges and responsive. I used 2% but you can use whatever percentages suit your layout.
-1๐
โIf for example, you wanted all charts created to be responsive, and resize when the browser window does, the following setting can be changed:โ
Chart.defaults.global.responsive = true;
โNow, every time we create a chart, options.responsive will be true.โ
Source: http://www.chartjs.org/docs/