Back in the day when web developers didn’t have to care about responsive layouts, life was easier in some cases. For example – charts. There are quite a lot of types of charts and in the beginnings of responsive web, creating responsive charts surely wasn’t a trivial task. But nowadays, given that there are thousands of different JavaScript libraries, it is no surprise that there are excellent libraries for charts. One of my favorite is Chart.js. In case you want to use it on WordPress, you can code it manually or use a WordPress Charts plugin.
Documentation on the website is quite extensive and explains everything there is about the library, but just in short, this is how it goes:
Load chart.js script, you can download it locally or use CDN link. After that, insert the global chart configuration – this is the code which starts with…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Chart.defaults.global = { // Boolean - Whether to animate the chart animation: true, // Number - Number of animation steps animationSteps: 60, // String - Animation easing effect // Possible effects are: // [easeInOutQuart, linear, easeOutBounce, easeInBack, easeInOutQuad, // easeOutQuart, easeOutQuad, easeInOutBounce, easeOutSine, easeInOutCubic, // easeInExpo, easeInOutBack, easeInCirc, easeInOutElastic, easeOutBack, // easeInQuad, easeInOutExpo, easeInQuart, easeOutQuint, easeInOutCirc, // easeInSine, easeOutExpo, easeOutCirc, easeOutCubic, easeInQuint, // easeInElastic, easeInOutSine, easeInOutQuint, easeInBounce, // easeOutElastic, easeInCubic] animationEasing: "easeOutQuart", // Boolean - If we should show the scale at all showScale: true, // Boolean - If we want to override with a hard coded scale scaleOverride: false, // ** Required if scaleOverride is true ** // Number - The number of steps in a hard coded scale scaleSteps: null, ... |
And now you can choose the chart – all you need to do is add data structure for any of the charts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", fillColor: "rgba(220,220,220,0.2)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: [65, 59, 80, 81, 56, 55, 40] }, ... |
The next step is to initiate the chart:
1 2 |
var ctx = document.getElementById("myChart").getContext("2d"); new Chart(ctx).Line(data); |
And then use HTML canvas element where the script will draw the chart:
1 |
<canvas id="myChart" width="400" height="400"></canvas> |
And that’s all. Have a look at my CodePen example with a working chart. I used example from the website documentation, with only difference that I activated the responsive mode (you can find it in global settings).