Open In App

Chart.js API Developer

Last Updated : 14 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Chart.js API Developer is a collection of methods, properties, and different events that we can use to create and manage the charts quite effectively.

API Methods

  • .destroy(): This method is used to destroy a chart instance, it will be useful when we don’t need the chart or in such cases where we have to replace the existing chart.
  • .update(mode?): This method is used to update the chart, If we have updated some data then it re-renders the chart and updates it.
  • .reset(): This method is used to reset the chart, it will set the chart to the initial state.
  • .render(): This method will re-draw the chart without any update.
  • .stop(): This method will stop the current animation on the chart.
  • .resie(width?, height?): We can use this method to resize the chart, this method is automatically called the container size resizes, but we can use this if we want to change the size of the canvas element through code.
  • .clear(): This method will clear the chart canvas.
  • .toBase64Image(type?, quality?): This method is useful when we want to save the chart as an image. We can have a PNG or high-quality JPEG image of the chart.
  • .getElementsAtEventForMode(e, mode, options, useFinalPosition): This method is used to get the chart element if an interaction event occurs, with the additional optional parameter we can filter the search process and use the end location of the interaction.
  • .getSortedVisibleDatasetMetas(): This method returns an array of the dataset metadata in the order they were drawn on the canvas, note that the hidden datasets won’t be visible through this method.
  • .getDatasetMeta(index): This method is used to get the metadata for a specific dataset.
  • .getVisibleDatasetCount: This method will return the count of the datasets that are currently visible on the chart.
  • .setDatasetVisibility(datasetIndex, visibility): This method is used to change the visibility of a specific dataset.
  • .toggleDataVisibility(index): This method will toggle the visibility of a specific data point and scroll all the datasets in the chart.
  • .getDataVisibility(index): This method will be used to check the visibility state of a data point across all the datasets in the chart.
  • .hide(datasetIndex, dataIndex?): This method is used to hide an entire dataset or a specific data point within a dataset, we also have options to animate that.
  • .show(datasetIndex, dataIndex): This method will used to show the hidden dataset or data point which is previously hidden. we also have options to animate that as well.
  • .setActiveElements(activeElements): This method is used to set active elements on the chart programmatically.
  • .isPluginEnabled(pluginId): This method is used to check if a specific plugin is enabled for the chart instance or not.

Example 1: In this example, we are using the .update() method, after 5 seconds the line chart gets updated automatically to the new data points.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>Chart.js Example</title>
    <script src=
    </script> <!-- Including Chart.js -->
</head>
 
<body>
 
    <!-- Canvas element where
    the chart will be rendered -->
    <canvas id="myChart" width="600"
    height="400">
    </canvas>
 
    <script>
        // JavaScript code goes here
 
        // Select the canvas element
        const ctx = document
            .getElementById('myChart')
            .getContext('2d');
 
        // Create a line chart
        const myLineChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['January',
                    'February',
                    'March',
                    'April',
                    'May',
                    'June',
                    'July'],
                datasets: [{
                    label: 'Monthly Sales',
                    data: [10, 20, 30, 40, 50, 60, 70],
                    borderColor: 'rgb(75, 192, 192)',
                    tension: 0.1
                }]
            },
            options: {}
        });
 
        // Function to update the chart
        function updateChart() {
            myLineChart.data.datasets[0].data[5] = 80;
            // Changing data for June
            myLineChart.update();
            // Updating the chart
        }
 
        // Call the update
        // function after 5 seconds
        setTimeout(updateChart, 5000);
 
    </script>
 
</body>
 
</html>


Output:
ezgifcom-video-to-gif

Example 2: In this example, We are using the .destory() method on a button, it will reset the chart and will recreate it.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>Chart.js Bar Chart Example</title>
    <script src=
    </script>
</head>
 
<body>
 
    <!-- Canvas element for the chart -->
    <canvas id="myBarChart"
    width="600" height="300">
    </canvas>
 
    <!-- Button to recreate the chart -->
    <button id="recreateChart">
          Recreate Chart
      </button>
 
    <script>
        // JavaScript code will be here
        let myBarChart;
        // Global variable to
        //  hold the chart instance
 
        // Function to create a chart
        function createChart(dataArray) {
            const ctx = document
                .getElementById('myBarChart')
                .getContext('2d');
            myBarChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Red',
                        'Blue',
                        'Yellow',
                        'Green',
                        'Purple',
                        'Orange'],
                    datasets: [{
                        label: 'Votes',
                        data: dataArray,
                        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: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
 
        // Initial chart creation
        createChart([12, 19, 3, 5, 2, 3]);
 
        // Event listener for the button
        document.getElementById('recreateChart')
            .addEventListener('click', function () {
                // Destroy the existing
                // chart if it exists
                if (myBarChart) {
                    myBarChart.destroy();
                }
 
                // Recreate the chart
                // with new random data
                const newData = Array.from({ length: 6 },
                    () => Math.floor(Math.random() * 20));
                createChart(newData);
            });
 
    </script>
</body>
 
</html>


Output:
ezgifcom-video-to-gif-(2)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads