Getting Started

Let’s get started with Chart.js!

Alternatively, see the example below or check samples.

Create a Chart

In this example, we create a bar chart for a single dataset and render it on an HTML page. Add this code snippet to your page:

  1. <div>
  2. <canvas id="myChart"></canvas>
  3. </div>
  4. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  5. <script>
  6. const ctx = document.getElementById('myChart');
  7. new Chart(ctx, {
  8. type: 'bar',
  9. data: {
  10. labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  11. datasets: [{
  12. label: '# of Votes',
  13. data: [12, 19, 3, 5, 2, 3],
  14. borderWidth: 1
  15. }]
  16. },
  17. options: {
  18. scales: {
  19. y: {
  20. beginAtZero: true
  21. }
  22. }
  23. }
  24. });
  25. </script>

You should get a chart like this:

demo

Let’s break this code down.

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 include Chart.js from a CDN.

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

Finally, we can create a chart. We add a script that acquires the myChart canvas element and instantiates new Chart with desired configuration: bar chart type, labels, data points, and options.

  1. <script>
  2. const ctx = document.getElementById('myChart');
  3. new Chart(ctx, {
  4. type: 'bar',
  5. data: {
  6. labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  7. datasets: [{
  8. label: '# of Votes',
  9. data: [12, 19, 3, 5, 2, 3],
  10. borderWidth: 1
  11. }]
  12. },
  13. options: {
  14. scales: {
  15. y: {
  16. beginAtZero: true
  17. }
  18. }
  19. }
  20. });
  21. </script>

You can see all the ways to use Chart.js in the step-by-step guide.