Chart.js - Where to place the global chart configuration?

I am trying to customize a chart chart diagram with the following code. Where in this place I put the code Chart.defaults.global = {} or Chart.defaults.global.responsive = true; ?

Chart.js docs can be found here: http://www.chartjs.org/docs/

 <!-- Chart.js --> <script src="http://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js"></script> <script> var ctx = document.getElementById("myChart").getContext("2d"); var data = { labels: ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7"], datasets: [ { label: "My Second dataset", fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", data: [86, 74, 68, 49, 42] } ] }; var options = { ... }; var myLineChart = new Chart(ctx).Line(data, options); </script> 
+8
javascript charts
source share
2 answers

There are two ways to accomplish what you are looking for. Thus

 var myLineChart = new Chart(ctx).Line(data, options); var options = Chart.defaults.global = { responsive: true, maintainAspectRatio: true }; 

or thus

 var myLineChart = new Chart(ctx).Line(data, { responsive: true, maintainAspectRatio: true }); 

However, to make it responsive, you need to add extra CSS

 canvas{ width: 100% !important; height: auto !important; } 

therefore no need for inline CSS

Working demo

According to @JustinXL's comment below and the latest version of Chart.js, there is no need for additional CSS, so check out the updated version.

Updated demo

+8
source share

You can set the parameters of your chart, but you can also set the global (as you requested) to avoid setting this specific property for each chart that you want to create.

You just need to install

 Chart.defaults.global.elements.responsive = true; 

before creating a chart, in your case, before

 var myLineChart = new Chart(ctx).Line(data, options); 

(PS: Chartjs V2)

+4
source share

All Articles