Getting Started

Let’s get started using Chart.js!

First, we need to have a canvas in our page. It’s recommended to give the chart its own container for responsiveness.

  1. <div>
  2. <canvas id="myChart"></canvas>
  3. </div>

Now that we have a canvas we can use, we need to include Chart.js in our page.

  1. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Now, we can create a chart. We add a script to our page:

  1. <script>
  2. const labels = [
  3. 'January',
  4. 'February',
  5. 'March',
  6. 'April',
  7. 'May',
  8. 'June',
  9. ];
  10. const data = {
  11. labels: labels,
  12. datasets: [{
  13. label: 'My First dataset',
  14. backgroundColor: 'rgb(255, 99, 132)',
  15. borderColor: 'rgb(255, 99, 132)',
  16. data: [0, 10, 5, 2, 20, 30, 45],
  17. }]
  18. };
  19. const config = {
  20. type: 'line',
  21. data: data,
  22. options: {}
  23. };
  24. </script>

Finally, render the chart using our configuration:

  1. <script>
  2. const myChart = new Chart(
  3. document.getElementById('myChart'),
  4. config
  5. );
  6. </script>

It’s that easy to get started using Chart.js! From here you can explore the many options that can help you customise your charts with scales, tooltips, labels, colors, custom actions, and much more.

Here the sample above is presented with our sample block:

Getting Started - 图1

config setup

  1. const config = {
  2. type: 'line',
  3. data: data,
  4. options: {}
  5. };
  1. const labels = [
  2. 'January',
  3. 'February',
  4. 'March',
  5. 'April',
  6. 'May',
  7. 'June',
  8. ];
  9. const data = {
  10. labels: labels,
  11. datasets: [{
  12. label: 'My First dataset',
  13. backgroundColor: 'rgb(255, 99, 132)',
  14. borderColor: 'rgb(255, 99, 132)',
  15. data: [0, 10, 5, 2, 20, 30, 45],
  16. }]
  17. };

Note

As you can see, some of the boilerplate needed is not visible in our sample blocks, as the samples focus on the configuration options.

All our examples are available online.

To run the samples locally you first have to install all the necessary packages using the npm ci command, after this you can run npm run docs:dev to build the documentation. As soon as the build is done, you can go to http://localhost:8080/samples/Getting Started - 图2 (opens new window) to see the samples.