ckportfolio.com - Canvas Visualization with PHP and JavaScript Library

Canvas Visualization with PHP and JavaScript Library

Setup

While we can use a similar approach as svg.php to manully build a similar Canvas visualization, there are numerous JavaScript libraries, such as Chart.js, dedicated to such efforts. We can begin by embedding the library components in graph.php, and setting up the <canvas> element:

graph.php

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css">

<h1 class="my-3">Graph</h1>
<canvas id="myChart" width="400" height="400" style="width:100%;"></canvas>

As per the provided instructions, we can initialize the library using the sample code:

graph.php

...
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            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: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
</script>

The result is a satisfying one, as the Chart.js plugin automatically builds an interactive bar chart:

Customizing Chart with PHP

There are many ways to further customize the sample chart, but we can focus on labels, label, and data sections of the JavaScript code to have the chart map to the correct forecast data.

graph.php

...
        labels: [],
        datasets: [{
            label: 'Temperature',
            data: [],
...

Upon renaming the label field and emptying the two lists, we can move onto collecting necessary data from the original forecast variable and organizing into the desired format using PHP:

data.php

<?

    $data = file_get_contents("https://api.darksky.net/forecast/fc14992ed7b63ebd6fcf1b740f6398a9/43.6532,-79.3832");
    $array = json_decode($data);
    $forecast = $array->daily->data;

    $chartLabels = array();
    $chartData = array();

    foreach ($forecast as $i => $entry) {

        $chartLabels[] = date("l", $entry->time);
        $chartData[] = round(($entry->temperatureLow - 32)*5/9);

    }

?>

Based our insights surrounding the forecast variable, we can return to data.php and construct two new PHP arrays dedicated to hosting individual dates and converted low temperature values. We can go back to graph.php and take advantage of these new variables:

graph.php

...
        labels: <?= json_encode($chartLabels) ?>,
        datasets: [{
            label: 'Temperature',
            data: <?= json_encode($chartData) ?>,
...

We are using json_encode(), the very opposite of the previously used json_decode() function, to convert the PHP arrays into JS compliant format and print directly into the source code. As front-end JS and PHP do not have a method to directly talk to one another, they alternatively converge in the HTML code.

Note that the chart now correctly displays the downloaded forecast information, thanks to PHP-based data transformation. One can further experiment with other options as documented by Chart.js to customize the look and feel.

Fin