Get the FREE Ultimate OpenClaw Setup Guide →

chartjs-overview

npx machina-cli add skill sjnims/chartjs-expert/chartjs-overview --openclaw
Files (1)
SKILL.md
9.1 KB

Chart.js Overview (v4.5.1)

Guidance for installing, configuring, and optimizing Chart.js v4.5.1 in web applications.

Installation

npm Installation

Install Chart.js via npm:

npm install chart.js

CDN Installation

Include Chart.js via CDN in HTML:

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

<!-- CDNJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.1/chart.umd.min.js"></script>

Basic Chart Creation

Create a chart with minimal configuration:

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  const ctx = document.getElementById('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],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
</script>

Key requirements:

  • A <canvas> element with an id
  • Wrap canvas in a container <div> for responsive sizing
  • Instantiate new Chart(ctx, config) with type, data, and options

Module Bundlers (Webpack, Rollup, Vite, Parcel)

Quick Start (All Components)

Import everything for rapid prototyping:

import Chart from 'chart.js/auto';

new Chart(ctx, {
  type: 'bar',
  data: { /* ... */ }
});

Warning: chart.js/auto disables tree-shaking. Use manual registration for production.

Bundle Optimization (Tree-Shaking)

Register only needed components for smaller bundles:

import {
  Chart,
  BarController,
  BarElement,
  CategoryScale,
  LinearScale,
  Legend,
  Tooltip
} from 'chart.js';

Chart.register(
  BarController,
  BarElement,
  CategoryScale,
  LinearScale,
  Legend,
  Tooltip
);

new Chart(ctx, {
  type: 'bar',
  data: { /* ... */ }
});

See references/tree-shaking.md for complete component lists per chart type.

Module Loader Support

CommonJS

Use dynamic import in CommonJS modules:

const { Chart } = await import('chart.js');

RequireJS (AMD)

Require the UMD build:

require(['path/to/chartjs/dist/chart.umd.min.js'], function(Chart) {
  const myChart = new Chart(ctx, { /* ... */ });
});

ES Modules (Script Tag)

Use type="module" with ESM CDN for modern browsers:

<script type="module">
  import Chart from 'https://cdn.jsdelivr.net/npm/chart.js/+esm';

  new Chart(ctx, {
    type: 'bar',
    data: { /* ... */ }
  });
</script>

Tree-shaking with ES Modules:

<script type="module">
  import {
    Chart,
    BarController,
    BarElement,
    CategoryScale,
    LinearScale
  } from 'https://cdn.jsdelivr.net/npm/chart.js/+esm';

  Chart.register(BarController, BarElement, CategoryScale, LinearScale);

  new Chart(ctx, {
    type: 'bar',
    data: { /* ... */ }
  });
</script>

See examples/production-bundle.html for complete working examples.

Configuration Structure

Every Chart.js configuration follows this structure:

const config = {
  type: 'line',           // Chart type
  data: {                 // Data and datasets
    labels: [],
    datasets: [{ data: [] }]
  },
  options: {},            // Chart options
  plugins: []             // Inline plugins
};

new Chart(ctx, config);

Global Configuration

Set defaults for all charts using Chart.defaults:

// Set font defaults globally
Chart.defaults.font.family = "'Inter', sans-serif";
Chart.defaults.font.size = 14;

// Set interaction mode globally
Chart.defaults.interaction.mode = 'nearest';
Chart.defaults.interaction.intersect = false;

// Set default for all line charts
Chart.defaults.datasets.line.showLine = false;
Chart.defaults.datasets.line.tension = 0.4;

// Set default for linear scales
Chart.defaults.scales.linear.min = 0;

// Plugin defaults
Chart.defaults.plugins.legend.position = 'bottom';
Chart.defaults.plugins.tooltip.backgroundColor = 'rgba(0, 0, 0, 0.8)';

Important: Changes to Chart.defaults only affect charts created after the change.

See references/configuration-patterns.md for advanced global configuration patterns.

Helper Functions

Import helpers separately from the helpers package for event handling and utilities:

import Chart from 'chart.js/auto';
import { getRelativePosition } from 'chart.js/helpers';

const chart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    onClick: (e) => {
      // Convert event position to chart coordinates
      const canvasPosition = getRelativePosition(e, chart);

      // Get data values at click position
      const dataX = chart.scales.x.getValueForPixel(canvasPosition.x);
      const dataY = chart.scales.y.getValueForPixel(canvasPosition.y);

      console.log(`Clicked at: (${dataX}, ${dataY})`);
    }
  }
});

Available helpers: getRelativePosition, isNullOrUndef, isArray, isObject, valueOrDefault, uid

See references/configuration-patterns.md for complete helper function reference.

Chart Instance Methods

Common methods available on chart instances for dynamic updates and manipulation:

const chart = new Chart(ctx, config);

// Update chart with new data
chart.data.datasets[0].data = [1, 2, 3, 4, 5];
chart.update();              // Default animation
chart.update('none');        // No animation (faster)
chart.update('active');      // Only active elements animate

// Resize chart
chart.resize();              // Auto-detect from container
chart.resize(800, 400);      // Set specific dimensions

// Reset to original state
chart.reset();

// Destroy chart instance (important for cleanup)
chart.destroy();

// Export chart as image
const image = chart.toBase64Image();                    // PNG
const jpeg = chart.toBase64Image('image/jpeg', 0.8);   // JPEG 80% quality

// Get elements at event position
const elements = chart.getElementsAtEventForMode(
  event,
  'nearest',
  { intersect: true },
  true
);

// Toggle dataset visibility
chart.hide(datasetIndex);
chart.show(datasetIndex);
chart.isDatasetVisible(datasetIndex);

Performance tip: Use update('none') for frequent updates to disable animation.

See references/instance-methods.md for complete method documentation and patterns.

Responsiveness

Charts are responsive by default, automatically resizing with their container:

new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    responsive: true,           // Resize with container (default: true)
    maintainAspectRatio: true,  // Keep aspect ratio (default: true)
    aspectRatio: 2,             // Width/height ratio (default: 2, radial: 1)
    resizeDelay: 0,             // Debounce resize updates in ms (default: 0)

    // Callback when chart resizes
    onResize: (chart, size) => {
      console.log(`Resized to ${size.width}x${size.height}`);
    }
  }
});

Container-based sizing: Chart.js gets dimensions from the canvas's parent container:

<div style="width: 80%; max-width: 1200px;">
  <canvas id="myChart"></canvas>
</div>

Flexbox/Grid containers: Set min-width: 0 on flex/grid children to prevent overflow:

<div style="display: grid; grid-template-columns: 1fr 1fr;">
  <div style="min-width: 0;"><canvas id="chart1"></canvas></div>
  <div style="min-width: 0;"><canvas id="chart2"></canvas></div>
</div>

Custom aspect ratios:

options: {
  aspectRatio: 1    // Square (radar, polar area)
  aspectRatio: 3    // Wide (timelines)
  aspectRatio: 0.5  // Tall (rankings)
}

Fixed-size charts:

options: {
  responsive: false,
  maintainAspectRatio: false
}
<canvas id="myChart" width="600" height="400"></canvas>

See references/configuration-patterns.md for responsive patterns and media query-like behavior.

Additional Resources

Reference Documentation:

  • references/tree-shaking.md - Complete component registration guide for all chart types
  • references/instance-methods.md - Chart instance methods, animation modes, and patterns
  • references/configuration-patterns.md - Global defaults, helpers, responsive patterns

Working Examples:

  • examples/basic-bar-chart.html - Bar chart examples (simple, horizontal, stacked)
  • examples/multi-dataset-line.html - Multi-dataset and area charts with real-time updates
  • examples/production-bundle.html - Tree-shaken builds with ESM imports

Source

git clone https://github.com/sjnims/chartjs-expert/blob/main/skills/chartjs-overview/SKILL.mdView on GitHub

Overview

Guides you through installing Chart.js v4.5.1, configuring it with npm or CDN, and choosing between auto-import or manual component registration. It covers bundle optimization, module loaders, and practical patterns for responsive charts and data updates.

How This Skill Works

The skill explains multiple installation paths (npm, CDN) and module loading options (ESM, CommonJS, RequireJS). It distinguishes between using chart.js/auto for rapid prototyping and manual registration for production-only components, then demonstrates creating a Chart instance with a minimal config and adapting it for tree-shaking by registering only needed components.

When to Use It

  • Starting a new Chart.js project and choosing between npm or CDN
  • Deciding between chart.js/auto and manual component registration
  • Optimizing bundle size with tree-shaking in modern bundlers
  • Using ES Modules, CommonJS, or RequireJS to load Chart.js
  • Setting up Chart.js v4.5.1 for responsive charts and data updates

Quick Start

  1. Step 1: Choose installation method (npm install chart.js or include via CDN)
  2. Step 2: Import Chart.js using either chart.js/auto for quick prototyping or manual registration for production
  3. Step 3: Add a canvas element, then instantiate a Chart with new Chart(ctx, config) and adjust options

Best Practices

  • Prefer manual registration in production to enable effective tree-shaking
  • If prototyping, chart.js/auto offers fastest setup but disable tree-shaking for production builds
  • Wrap the canvas in a container div to enable responsive sizing
  • Keep Chart.js version 4.5.1 consistent with your project and reference docs
  • Use appropriate imports (BarController, BarElement, CategoryScale, etc.) to minimize bundle size

Example Use Cases

  • Prototype a quick bar chart by npm install chart.js and importing Chart from 'chart.js/auto', then new Chart(ctx, config)
  • Create a lean bundle by manually registering only needed components and Chart.register(BarController, BarElement, CategoryScale, LinearScale, Legend, Tooltip)
  • Use the ES Module CDN +esm path to load Chart.js and register components for production
  • Load Chart.js via CommonJS with dynamic import: const { Chart } = await import('chart.js') and instantiate
  • Integrate Chart.js in a RequireJS environment by loading the UMD build and creating a new Chart with the proper context

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers