Home >Web Front-end >JS Tutorial >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.
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.
Before we begin, ensure you have the following:
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>
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] })); }
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!