Example: Using Chart.js in Directual

Step 1: Preparing data

"Create a data structure named Population with two columns: date and value, and populate it.

2. Create an endpoint for accessing this data structure

Now you have:

  1. A data structure called Population

  2. An endpoint for accessing this data structure

Step 2: Creating plugin

Create a new plugin on the main page.

In the Parameters sections, set the JS library to: "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.min.js". This library will be loaded on the open page, allowing you to utilize functions from it.

Add a new component in the Web-component section

Be sure to include the following two parameters:

  • 'Endpoint' with a type of 'API-endpoint' to access data from any API

  • 'Title' for rendering the name of your graphic.

Insert the code to 'initialize' section:

function(instance, context) {

  div = $('<canvas id="myChart"></canvas>');
  div.css('width', '100%');
  div.css('height', '100%');
  div.css('cursor', 'pointer');
  
  instance.canvas.append(div);

}

Then insert the code bellow to the 'Update' section:

function(instance, properties, context) {  var ctx = document.getElementById('myChart');
var data = context.endpoint || []
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: data.map(s=>s.date),
        datasets: [{
            label: '# of ' + context.title,
            data: data.map(s=>parseInt(s.value)),
            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
            }
        }
    }
}); }

Add your plugin to your app in the 'Status and action' section:

Insert your app's name in the 'Apps where the plugin is available' field. The new plugin will then be available in these apps.

Last step: Use your plugin in your app!

Open your app, and go to the Plugins section and install it.

Move your component from the right section to your page.

Click on 'View page'.

Voilà!

Last updated