Skip to content
Advertisement

HorizontalBar chart is displayed below canvas when I set height with style attribute for chart div (Chart.js 2.9.4)

If I set height with style attribute for chart div

<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>

chart is looking like that (chart is displayed below canvas):

var barChartData = {
  labels: [""],
  datasets: [{
      label: "1",
      backgroundColor: "rgba(68,222,166,1)",
      barThickness: 50,
      data: [177]
    },
    {
      label: "2",
      barThickness: 50,
      backgroundColor: "rgba(218, 65, 102, 1)",
      data: [170]
    }
  ]
};

var optionsBar = {
  legend: false,
  title: {
    display: false    
  },
  scales: {
    xAxes: [{
      stacked: true,
      display: false
    }],
    yAxes: [{
      stacked: true,
      display: false
    }]
  }
};


var ctx = document.getElementById("chart");
var myChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: barChartData,
  options: optionsBar
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>

<body style="background-color: grey;">
<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>
</body>

How to fix that?

Advertisement

Answer

It’s showing like this because canvas’s aspect ratio is changing automatically with window size but you’ve set your div to a specific height of 100px. That’s why canvas has placed outside of the div while window size is extending. Just to get rid of that problem, set maintainAspectRatio: false in your option in this way:

var barChartData = {
    labels: [""],
    datasets: [{
        label: "1",
        backgroundColor: "rgba(68,222,166,1)",
        barThickness: 50,
        data: [177]
    },
    {
        label: "2",
        barThickness: 50,
        backgroundColor: "rgba(218, 65, 102, 1)",
        data: [170]
    }
    ]
};

var optionsBar = {
    maintainAspectRatio: false,
    legend: false,
    title: {
        display: false
    },
    scales: {
        xAxes: [{
            stacked: true,
            display: false
        }],
        yAxes: [{
            stacked: true,
            display: false
        }]
    }
};


var ctx = document.getElementById("chart");
var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: barChartData,
    options: optionsBar
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>

<body style="background-color: grey;">
    <div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>
</body>
Advertisement