Note: Please view the related Pen for this post: Auto-filling Charts with Chart.js

Note: You must be familiar with the Line Chart Introduction to understand this post, but it’s a very quick and simple read.

Chart.js is a simple yet feature-rich Javascript library that embeds charts and graphs in websites. Recently, the author/s of Chart.js added a responsive setting that redraws charts by width, but they are fixed to the original aspect ratio of the canvas. While the new feature almost fit the bill for a project at work, I wanted the size of the chart to always autofill its region, regardless of the original aspect ratio. This is not supported out of the box, unfortunately.

Luckily it is easy to implement your own auto-filling responsive charts, and I’ve put an example in this Auto-filling Charts with Chart.js Pen (not embedded due to wordpress.com restrictions).

Chart JS Chart
Chart JS chart.

The key to this functionality are the setChartDimensions() function and window’s resize event. setChartDimensions() calculates the height and width of the region for the chart to fill and sets the canvas’ width and height attributes to these calculated values. Using jQuery, this is very simple:

function setChartDimensions() {
  var width = $("section").width(),
      height = $("footer").offset().top - $("canvas").offset().top - 20;
  if (currentChart) {
    currentChart.chart.aspectRatio = width / height;
  } else {
    $("canvas").attr("width", width);
    $("canvas").attr("height", height);
  }
}

This function should be called before creating the chart and when the window is resized. On resize, rather than recreating the graph, refresh it with built-in Chart.js functions:

$(window).resize(function() {
  if (currentChart) {
    setChartDimensions();
    currentChart.stop();
    currentChart.resize(currentChart.render, true);
  }
});

When you are creating your chart, you must save it in a variable that is available to both resize and setChartDimensions(). I’ve done that in the Pen with the currentChart variable. Good luck!