Home >Web Front-end >JS Tutorial >Integrating CanvasJS with DataTables

Integrating CanvasJS with DataTables

Barbara Streisand
Barbara StreisandOriginal
2024-10-01 20:17:03782browse

CanvasJS is a JavaScript charting library that allows you to create interactive and responsive charts, while DataTables is a jQuery plugin that enhances HTML tables with advanced interaction controls like pagination, filtering, and sorting. Combining these two tools in a dashboard enables real-time data visualization, making it easier to analyze and interpret data trends and patterns through interactive and visually appealing charts that update dynamically based on the table data.

Integrating CanvasJS with DataTables

In this tutorial, we’ll walk through the process of integrating CanvasJS with DataTables to create a dynamic pie chart that updates based on the data in the table. This example will use a simple HTML structure and JavaScript code to demonstrate the integration.

Prerequisites

Before we begin, ensure you have the following:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • CanvasJS and DataTables libraries included in your project.

Step 1: Setting Up the HTML

First, create an HTML file with a container for the chart and a table for the data.

<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
    </tr>
    <tr>
      <td>Garrett Winters</td>
      <td>Accountant</td>
    </tr>
    <!-- Add more rows as needed -->
  </tbody>
</table>

Step 2: Creating the JavaScript File

Create a script.js file and add the following code to initialize the DataTable and CanvasJS chart.

// Create DataTable
var table = new DataTable('#dataTable');

// Create chart
var chart = new CanvasJS.Chart('chartContainer', {
        animationEnabled: true,
    theme: "light2",
    title: {
        text: 'Staff Count Per Position'
    },
    data: [
        {
            type: "pie",
          dataPoints: chartData(table)
        }
    ]
});
chart.render();

// On each draw, update the data in the chart
table.on('draw', function () {
    chart.options.data[0].dataPoints = chartData(table);
    chart.render();
});

function chartData(table) {
    var counts = {};

    // Count the number of entries for each position
    table
        .column(1, { search: 'applied' })
        .data()
        .each(function (val) {
            if (counts[val]) {
                counts[val] += 1;
            }
            else {
                counts[val] = 1;
            }
        });

    return Object.entries(counts).map((e) => ({
        label: e[0],
        y: e[1]
    }));
}
  • HTML Structure: The HTML file includes a container for the chart (chartContainer) and a table (example) with sample data.
  • DataTable Initialization: The DataTable is initialized using the DataTable constructor.
  • CanvasJS Chart Initialization: A new CanvasJS chart is created with the specified options, including the chart type (pie) and data points.
  • Dynamic Data Update: The draw event of the DataTable is used to update the chart data points whenever the table is redrawn. The chartData function calculates the number of entries for each position and updates the chart accordingly.

Step 3: Test and Debug

  • Open the HTML file in a web browser: Ensure that the chart and table are displayed correctly.
  • Check for errors: Open the browser’s developer console to check for any JavaScript errors.
  • Verify dynamic updates: Add or remove rows from the table and ensure that the chart updates accordingly.
jsfiddle.net

By following these steps, you have successfully integrated CanvasJS with DataTables to create a dynamic pie chart that updates based on the data in the table. This integration allows you to visualize data in real-time, making it easier to analyze and understand the information presented in the DataTable. Feel free to customize the chart and table as needed for your specific use case. Happy coding!

The above is the detailed content of Integrating CanvasJS with DataTables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Nextjs vs ReactNext article:Nextjs vs React