[Chartjs]-How to make a chart scroll horizontally (when using Chart.js)

6👍

a

chart.js docs: "The following examples do not work:"

= Any canvas sizes like (<canvas style="width: 100px;..") + position absolute and other tricks will not work her.

b

Chart.js uses its parent container to update the canvas render and
display sizes.
However, this method requires the container to be
relatively positioned and dedicated to the chart canvas only.
Responsiveness can then be achieved by setting relative values for the
https://www.chartjs.org/docs/latest/configuration/responsive.html#important-note

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
    <canvas id="chart"></canvas>
</div>

= set any size you want for chart-container.

c

  • maintainAspectRatio – by default true (Maintain the original canvas aspect ratio (width / height) when resizing).

  • responive – by deafult true (Resizes the chart canvas when its container does)

a+b+c

I do not know why other stackoverflow answers give such "complex" solutions. The overflow-x her works like any other block-level element (Put 800px w image inside 600px W div = 200px overflow-x).

"hello world" example

Specific for overflow add extra wrapper to chart-container:

<div style="overflow-x: scroll">
  <div class="chart-container" style="position: relative;  width:900px;">
    <canvas id="chart"></canvas>
  </div>
</div>

When the screen width will be smaller than 900px you get horizontal scroll (On mobile for example):

enter image description here

** Use CSS breakpoints to resize the container on mobile if you want.

/* data */
var data = {
  labels: ["Africa", "Asia", "Europe", "America"],
  datasets: [{
    /* data */
    label: "Data label",
    backgroundColor: ["red", "#8e5ea2","#3cba9f", '#1d49b8'],
    data: [5.0,6.7,7.5, 8.6, 3.3, 4.4, 4.5]
  }]
};

var options = {
  responsive: true,
  maintainAspectRatio: true,
  title: {
    text: 'Hello',
    display: true
  },
  scales: {
    xAxes: [{
      stacked: false,
      ticks: {

      },
    }],
    yAxes: [{
      stacked: true,
      ticks: {

      }
    }]
  }
};

var myChart = new Chart(document.getElementById("chart"), {
  type: 'bar',
  data: data,
  options: options
});

document.getElementById('submitChange').addEventListener('click', function() {
  console.log("before color: " + myChart.data.datasets[0].backgroundColor[0]);
  myChart.data.datasets[0].backgroundColor[0] = "green";
  myChart.update();
});
div{
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div style="overflow-x: scroll">
  <div class="chart-container" style="position: relative;  width:900px;">
    <canvas id="chart"></canvas>
  </div>
</div>

-1👍

Use “overflow-x:scroll;” instead of “overflow:scroll;”

Leave a comment