| commit | author | age | ||
| 83c3f6 | 1 | # Usage |
| SP | 2 | Chart.js can be used with ES6 modules, plain JavaScript and module loaders. |
| 3 | ||
| 4 | ## Creating a Chart | |
| 5 | ||
| 6 | To create a chart, we need to instantiate the `Chart` class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart. Here's an example. | |
| 7 | ||
| 8 | ```html | |
| 9 | <canvas id="myChart" width="400" height="400"></canvas> | |
| 10 | ``` | |
| 11 | ||
| 12 | ```javascript | |
| 13 | // Any of the following formats may be used | |
| 14 | var ctx = document.getElementById("myChart"); | |
| 15 | var ctx = document.getElementById("myChart").getContext("2d"); | |
| 16 | var ctx = $("#myChart"); | |
| 17 | var ctx = "myChart"; | |
| 18 | ``` | |
| 19 | ||
| 20 | Once you have the element or context, you're ready to instantiate a pre-defined chart-type or create your own! | |
| 21 | ||
| 22 | The following example instantiates a bar chart showing the number of votes for different colors and the y-axis starting at 0. | |
| 23 | ||
| 24 | ```html | |
| 25 | <canvas id="myChart" width="400" height="400"></canvas> | |
| 26 | <script> | |
| 27 | var ctx = document.getElementById("myChart"); | |
| 28 | var myChart = new Chart(ctx, { | |
| 29 | type: 'bar', | |
| 30 | data: { | |
| 31 | labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], | |
| 32 | datasets: [{ | |
| 33 | label: '# of Votes', | |
| 34 | data: [12, 19, 3, 5, 2, 3], | |
| 35 | backgroundColor: [ | |
| 36 | 'rgba(255, 99, 132, 0.2)', | |
| 37 | 'rgba(54, 162, 235, 0.2)', | |
| 38 | 'rgba(255, 206, 86, 0.2)', | |
| 39 | 'rgba(75, 192, 192, 0.2)', | |
| 40 | 'rgba(153, 102, 255, 0.2)', | |
| 41 | 'rgba(255, 159, 64, 0.2)' | |
| 42 | ], | |
| 43 | borderColor: [ | |
| 44 | 'rgba(255,99,132,1)', | |
| 45 | 'rgba(54, 162, 235, 1)', | |
| 46 | 'rgba(255, 206, 86, 1)', | |
| 47 | 'rgba(75, 192, 192, 1)', | |
| 48 | 'rgba(153, 102, 255, 1)', | |
| 49 | 'rgba(255, 159, 64, 1)' | |
| 50 | ], | |
| 51 | borderWidth: 1 | |
| 52 | }] | |
| 53 | }, | |
| 54 | options: { | |
| 55 | scales: { | |
| 56 | yAxes: [{ | |
| 57 | ticks: { | |
| 58 | beginAtZero:true | |
| 59 | } | |
| 60 | }] | |
| 61 | } | |
| 62 | } | |
| 63 | }); | |
| 64 | </script> | |
| 65 | ``` | |