Skip to content

Installing and Including Chart.js

Before starting to use Chart.js, we need to include it in our project. Chart.js provides multiple inclusion methods to adapt to different development environments and needs.

Inclusion Methods Overview

Chart.js provides the following inclusion methods:

  1. CDN Inclusion: The simplest and quickest method, suitable for rapid prototyping
  2. NPM Installation: Suitable for modern frontend projects, facilitating version management and build optimization
  3. Download Files: Suitable for offline environments or when complete control over files is needed
  4. Package Managers: Such as Yarn, Bower, etc.

This is the simplest inclusion method, especially suitable for beginners and rapid prototyping.

1. Add the following code to the <head> tag of your HTML file:

html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chart.js Example</title>
    <!-- Include Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <!-- Your page content -->
    <canvas id="myChart"></canvas>

    <script>
        // Your Chart.js code
        const ctx = document.getElementById('myChart').getContext('2d');
        const 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, 205, 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, 205, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    </script>
</body>
</html>

2. Use Specific Version

If you need to use a specific version of Chart.js, you can specify the version number:

html
<!-- Use specific version -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0"></script>

<!-- Use latest version -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

For projects using modern frontend build tools (like Webpack, Vite, etc.), installing via NPM is recommended.

1. Install Chart.js

Open a terminal in your project root directory and run the following command:

bash
npm install chart.js

2. Include in Your Project

The inclusion method varies slightly depending on the framework and build tools you use:

Include in JavaScript files:

javascript
// Include Chart.js
import Chart from 'chart.js/auto';

// Or only include needed chart types to reduce bundle size
import { Chart, BarController, BarElement, CategoryScale, LinearScale, Title, Tooltip, Legend } from 'chart.js';

// Register needed components
Chart.register(BarController, BarElement, CategoryScale, LinearScale, Title, Tooltip, Legend);

// Create chart
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        // ... data configuration
    },
    options: {
        // ... options configuration
    }
});

Include in CommonJS environment:

javascript
// Include Chart.js
const Chart = require('chart.js/auto');

// Create chart
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    // ... configuration
});

Method 3: Download Files Locally

If you want complete control over Chart.js files or use it in an offline environment, you can choose to download files locally.

1. Download Chart.js

Visit Chart.js Official Website or GitHub Repository to download the latest version files.

Or download directly from CDN:

bash
# Download latest version
curl -O https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.js

# Or download compressed version
curl -O https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js

2. Copy Files to Project

Copy the downloaded Chart.js files to your project directory, for example:

your-project/
├── js/
│   ├── chart.js
│   └── main.js
├── css/
│   └── style.css
└── index.html

3. Include in HTML

Add the following code to your HTML file:

html
<script src="js/chart.umd.min.js"></script>

Method 4: Use Package Managers

Install using Yarn:

bash
yarn add chart.js

Install using Bower:

bash
bower install chart.js

Version Selection

Chart.js has multiple versions available:

  • Chart.js 4.x: Latest version, performance optimizations and new features
  • Chart.js 3.x: Stable version, widely used
  • Chart.js 2.x: Older version, but still widely used

For new projects, using the latest version of Chart.js is recommended.

Verify Installation

Regardless of which method you use to include Chart.js, you can verify if installation was successful in the following way:

html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Chart.js Test</title>
    <!-- Include Chart.js based on your chosen method -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <h1>Chart.js Test</h1>
    <canvas id="testChart"></canvas>

    <script>
        // Check if Chart.js is loaded correctly
        if (typeof Chart !== 'undefined') {
            console.log('Chart.js version:', Chart.version);

            // Create a simple chart to verify functionality
            const ctx = document.getElementById('testChart').getContext('2d');
            const testChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['A', 'B', 'C'],
                    datasets: [{
                        label: 'Test Data',
                        data: [10, 20, 30],
                        backgroundColor: 'rgba(54, 162, 235, 0.2)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            console.log('Chart.js has been successfully loaded and is working!');
        } else {
            console.error('Chart.js is not loaded correctly!');
        }
    </script>
</body>
</html>

If the console outputs "Chart.js has been successfully loaded and is working!" and a bar chart appears on the page, Chart.js has been successfully installed and can be used.

Important Notes

  1. Network Connection: Using CDN method requires a stable network connection
  2. Version Compatibility: Ensure the Chart.js version used is compatible with project requirements
  3. File Path: When including locally, ensure file paths are correct
  4. Browser Cache: If you update the Chart.js version, you may need to clear browser cache
  5. Security: When using CDN, it's recommended to specify integrity check (integrity)
html
<script
  src="https://cdn.jsdelivr.net/npm/chart.js"
  integrity="sha256-8n5Wv8+w5ZK1KqJn3Fh2hF8b2V6b7r4n4q8n8n8n8n8="
  crossorigin="anonymous">
</script>

With the above methods, you can successfully include Chart.js in your project and start using it to create various data visualization charts.

Content is for learning and research only.