📜  chart.js src - Javascript (1)

📅  最后修改于: 2023-12-03 15:14:08.089000             🧑  作者: Mango

Chart.js

Chart.js is a JavaScript library for creating beautiful charts and graphs easily. It is built on top of HTML5 canvas and comes with a simple yet powerful API.

Installation

Chart.js can be installed using npm or included in your project via CDN.

Install via npm
npm install chart.js --save
Include via CDN
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Usage

Creating a chart is as simple as creating a canvas element and passing in the data and options.

<canvas id="myChart"></canvas>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});

This will create a simple bar chart with 6 labels and corresponding data points.

Chart Types

Chart.js supports a variety of chart types including bar, line, radar, pie, doughnut, and polar area charts.

Documentation

The documentation for Chart.js is comprehensive and easy to follow. It covers everything from setting up your chart to customizing colors and styles.

View Chart.js documentation

Conclusion

Chart.js is an excellent choice for creating simple and beautiful charts and graphs in JavaScript. Its simplicity and ease of use make it a popular choice among developers.