How to resize a chart in Chart.js?

by moriah.medhurst , in category: JavaScript , a year ago

How to resize a chart in Chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by kavon , a year ago

@moriah.medhurst 

In Chart.js, you can resize a chart by setting the width and height options in the chart's configuration object. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var chart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    // Set the chart's width and height
    responsive: false,
    maintainAspectRatio: false,
    width: 400,
    height: 200
  }
});


Alternatively, you can use the resize method to dynamically resize the chart. This can be useful if you want to resize the chart in response to changes in the size of the container element or the browser window.

1
2
// Resize the chart to the size of its container element
chart.resize();


Note that if you are using the responsive option, you should set it to false and use the maintainAspectRatio option to disable the default behavior of maintaining the aspect ratio when resizing the chart. This will allow you to set the width and height options independently.

Member

by dasia , 4 months ago

@moriah.medhurst 

To resize a chart in Chart.js, you can either directly set the width and height options in the chart's configuration object or use the resize method.

  1. Setting the width and height options: Set the responsive option to false to disable the chart's responsiveness. Set the maintainAspectRatio option to false to allow independent width and height settings. Set the width and height options to the desired values. var chart = new Chart(ctx, { type: 'bar', data: data, options: { responsive: false, maintainAspectRatio: false, width: 400, height: 200 } });
  2. Using the resize method: Call the resize method on the chart instance. This will dynamically resize the chart to fit the size of its container element. // Resize the chart to the size of its container element chart.resize();


Remember to adjust the responsive option accordingly if you want the chart to be responsive to changes in the container size or browser window.