DEV Community

Cover image for Integrating CanvasJS with DataTables
Vishwas R
Vishwas R

Posted on

Integrating CanvasJS with DataTables

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.

CanvasJS Chart 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>
Enter fullscreen mode Exit fullscreen mode

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]
    }));
}
Enter fullscreen mode Exit fullscreen mode
  • 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.

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!

Top comments (0)