[Chartjs]-Why is chart.js canvas not respecting the padding of the container element?

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.

JSFIDDLE EXAMPLE

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/

Leave a comment