[Chartjs]-Integrate chart.js with single javascript file

0👍

Well I had a go at this and it seems the best bet is to install the Chart.min.js locally on your server – I grabbed it from Github – the link is on the chartjs.org site ( which you have obviously been to already)

Download it and save it where appropriate for your setup.

Controller – Chart.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chart extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $this->load->helper('url');
        $this->load->view('chart_view');
    }
}

View – chart_view.php

<canvas id="myChart"></canvas>

// Load the Chart.min.js locally on the server
// Note: make sure you have application/config/config.php config['base_url'] correctly set.

<script src="<?=base_url('assets/chart/2.8.0/Chart.min.js');?>"></script>

<script type="application/javascript">
    let ctx = document.getElementById('myChart').getContext('2d');
    let 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>

And I got a nice little chart showing up.
See if that works for you.

Leave a comment