Search code examples
chart.jsvue-chartjs

chartjs not following height when parent's height is 200px


Im using vue-chartjs to display a doughnut chart. I want the chart to follow the parent's height(200px).

I tried to set maintainAspectRatio to false in the option, it shrinked, but still not fit into the parent div.

This is the option I'm using for the chart.

import { Pie } from 'vue-chartjs'

export default {
  extends: Pie,
  name: 'Pie_Chart',
  props: ["rating"],
  mounted() {
    this.renderChart({
      legend: { display: false },
      datasets: [{
        backgroundColor: ['#DAE02A', '#6D6D6D'],
        data: [1000, this.$props.rating],
        borderWidth: 0
      }]
    }, {
      responsive:true,
      maintainAspectRatio: false,
      cutoutPercentage: 80,
      legend: { display: false },
      tooltips: { enabled: false },
      hover: { mode: false },
    })
  },
}

Although the width of the chart has fit into the parent div, but there are still some empty space above and below the chart which causes the height to not fit into the parent div.

working sample of my problem

before adding maintainAspectRatio before adding maintainAspectRatio after adding maintainAspectRatio after adding maintainAspectRatio after setting width of parent after setting width of parent generated html enter image description here


Solution

  • Since you haven't provided a working example of your problem it can't be directly solved.

    The result you want is possible, so here's a snippet showing a doughnut chart sized to exactly 200px by 200px (I've added a background-color to the div for clarity):

    new Chart(document.getElementById("chart"), {
      type: "doughnut",
      data: {
        datasets: [{
          data: [1, 4]
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutoutPercentage: 80,
        legend: {
          display: false
        },
        tooltips: {
          enabled: false
        },
        hover: {
          mode: false
        }
      }
    });
    div {
      background-color: #ccf;
      width: 200px;
      height: 200px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
    <div>
      <canvas id="chart"></canvas>
    </div>