0
votes

I'm trying to build a doughnut chart with chart.js but the chart container is bigger than the chart canvas and it makes it harder to design stuff around it...

is there any option to make the chart and the container the same height and width?

settings:

var option = {
   rotation: 1 * Math.PI,
    circumference: 1 * Math.PI,
  responsive: true,
  aspectRatio:2,
   title: { display: false },
  legend: { display: false },
  scales: {
    xAxes: [
          {
            gridLines: {
              drawBorder: false,
              display: false,
            },
            ticks: {
              display: false,
            },
          },
        ],
        yAxes: [
          {
            gridLines: {
              drawBorder: false,
              display: false,
            },
            ticks: {
              display: false,
            },
          },
        ],
  }
};

Code Pen: https://codepen.io/ronmara/pen/vYGeJyo

You can see there is a little gap between the left, right, and bottom border of the div.

2

2 Answers

1
votes

It's a bit of a hacky solution, but setting layout.padding to -10 fits your doughnut more neatly in your container:

var data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
  datasets: [
    {
      label: "Dataset #1",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 20, 81, 56, 55, 40]
    }
  ]
};

var option = {
  rotation: 1 * Math.PI,
  circumference: 1 * Math.PI,
  responsive: true,
  aspectRatio: 2,
  title: { display: false },
  legend: { display: false },
  layout: {
    padding: -10
  },
  scales: {
    xAxes: [
      {
        gridLines: {
          drawBorder: false,
          display: false
        },
        ticks: {
          display: false
        }
      }
    ],
    yAxes: [
      {
        gridLines: {
          drawBorder: false,
          display: false
        },
        ticks: {
          display: false
        }
      }
    ]
  }
};

Chart.Doughnut("chart_0", {
  options: option,
  data: data
});
body {  
  background: white;
  padding: 16px;
}

canvas {
  border: 1px dotted red;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div class="chart-container" style="position: relative; height:16vh; width:32vh">
<canvas id="chart_0"></canvas>
</div>
-1
votes

I got it centered by removing the inline styles and adding them to the class attached to the div.

I also added the layout.padding into your options.

layout: {
  padding: {
   left: 0,
   top: 10,
   right: 10,
   bottom: 0
}},

Adding codepen for reference. https://codepen.io/robert9111/pen/abNVxWY