Get the FREE Ultimate OpenClaw Setup Guide →

chartjs-configuration

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

Chart.js Configuration (v4.5.1)

Comprehensive guide to configuring Chart.js options, animations, legends, tooltips, and interactions.

Configuration Structure

const config = {
  type: 'line',
  data: { /* datasets, labels */ },
  options: {
    responsive: true,
    maintainAspectRatio: true,
    aspectRatio: 2,
    events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
    onClick: (event, elements, chart) => { /* handle click */ },
    onHover: (event, elements, chart) => { /* handle hover */ },
    plugins: {
      legend: { /* legend options */ },
      tooltip: { /* tooltip options */ },
      title: { /* title options */ }
    },
    scales: { /* axis options */ },
    animation: { /* animation options */ },
    interaction: { /* interaction options */ },
    layout: { /* layout options */ }
  },
  plugins: []  // Inline plugins
};

Responsive Configuration

Namespace: options

OptionTypeDefaultDescription
responsivebooleantrueResize with container
maintainAspectRatiobooleantrueKeep aspect ratio
aspectRationumber2 (radial: 1)Width/height ratio
resizeDelaynumber0Debounce resize (ms)
onResizefunctionnullCallback on resize

Container Requirements

Chart.js requires the container to be relatively positioned and dedicated to the chart canvas only:

<div class="chart-container" style="position: relative; height: 40vh; width: 80vw">
  <canvas id="chart"></canvas>
</div>

Flexbox/Grid Layout

To prevent overflow in flexbox/grid layouts, set min-width: 0 on the container:

<div class="grid-container" style="display: grid">
  <div class="chart-container" style="min-width: 0">
    <canvas id="chart"></canvas>
  </div>
</div>

For fixed-size charts, set responsive: false and define canvas dimensions directly.

See examples/responsive-chart.html for complete responsive setup including print handling.

Legend Configuration

Namespace: options.plugins.legend

OptionTypeDefaultDescription
displaybooleantrueShow legend
positionstring'top'top, bottom, left, right, chartArea
alignstring'center'start, center, end
reversebooleanfalseReverse order
maxHeightnumber-Maximum height (px)
maxWidthnumber-Maximum width (px)
fullSizebooleantrueTake full canvas width/height
rtlboolean-Right-to-left rendering
onClickfunction-Click handler
onHoverfunction-Hover handler
onLeavefunction-Mouse leave handler

Legend Labels

labels: {
  boxWidth: 40,
  boxHeight: 12,
  color: '#666',
  font: { size: 12 },
  padding: 10,
  usePointStyle: false,
  pointStyle: 'circle',
  filter: (item, data) => item.text !== 'Hidden',  // Filter items
  sort: (a, b, data) => a.text.localeCompare(b.text)  // Sort items
}

Hide Legend

plugins: { legend: { display: false } }

For custom click handlers and Legend Item Interface, see references/legend-customization.md.

Tooltip Configuration

Namespace: options.plugins.tooltip

OptionTypeDefaultDescription
enabledbooleantrueEnable on-canvas tooltips
externalfunctionnullExternal (HTML) tooltip handler
modestringinteraction.modepoint, index, dataset, nearest
intersectbooleaninteraction.intersectRequire intersection
positionstring'average'average, nearest, or custom
backgroundColorColor'rgba(0,0,0,0.8)'Background color
paddingnumber6Padding inside tooltip
cornerRadiusnumber6Border radius
displayColorsbooleantrueShow color boxes

Tooltip Callbacks

callbacks: {
  title: (items) => items[0].label,
  label: (context) => `${context.dataset.label}: ${context.parsed.y}`,
  footer: (items) => `Total: ${items.reduce((a, b) => a + b.parsed.y, 0)}`
}

Additional callbacks: beforeTitle, afterTitle, beforeBody, afterBody, beforeLabel, afterLabel, labelColor, labelTextColor, labelPointStyle, beforeFooter, afterFooter.

Disable Tooltips

plugins: { tooltip: { enabled: false } }

For external HTML tooltips, custom positioners, and the full Tooltip Model, see references/tooltip-customization.md and examples/custom-tooltip.html.

Title Configuration

Namespace: options.plugins.title

plugins: {
  title: {
    display: true,
    text: 'Chart Title',
    color: '#666',
    font: { size: 16, weight: 'bold' },
    padding: { top: 10, bottom: 10 },
    align: 'center',      // start, center, end
    position: 'top',      // top, bottom, left, right
    fullSize: true        // Take full canvas width
  },
  subtitle: {
    display: true,
    text: 'Chart Subtitle',
    color: '#999',
    font: { size: 12 }
  }
}

Animation Configuration

Chart.js animation has three configuration levels:

KeyNamespacePurpose
animationoptions.animationBase animation settings
animationsoptions.animationsPer-property animations
transitionsoptions.transitionsMode-specific animations

Base Animation

animation: {
  duration: 1000,
  easing: 'easeOutQuart',
  delay: 0,
  loop: false,
  onProgress: (animation) => { /* during animation */ },
  onComplete: (animation) => { /* when complete */ }
}

Per-Property Animations

animations: {
  tension: {
    duration: 1000,
    easing: 'linear',
    from: 1,
    to: 0,
    loop: true
  },
  colors: {
    type: 'color',
    duration: 500,
    from: 'transparent'
  }
}

Transitions

Control animations for specific modes (active, hide, show, reset, resize):

transitions: {
  active: { animation: { duration: 400 } },
  resize: { animation: { duration: 0 } },
  show: {
    animations: {
      colors: { from: 'transparent' },
      visible: { type: 'boolean', duration: 0 }
    }
  }
}

Disable Animations

animation: false  // Disable all
// Or per-mode:
transitions: { active: { animation: { duration: 0 } } }

Easing Functions

linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInElastic, easeOutElastic, easeInOutElastic, easeInBack, easeOutBack, easeInOutBack, easeInBounce, easeOutBounce, easeInOutBounce

For animation callbacks and advanced patterns, see references/advanced-animations.md.

Interaction Configuration

Namespace: options.interaction

OptionTypeDefaultDescription
modestring'nearest'How to find elements
intersectbooleantrueMust intersect element
axisstring'x'x, y, xy, or r
includeInvisiblebooleanfalseInclude hidden elements

Interaction Modes

ModeDescription
'point'Elements at same position
'index'Elements at same index
'dataset'Elements in same dataset
'nearest'Nearest element
'x'Elements at same x-axis value
'y'Elements at same y-axis value

Event Handling

Namespace: options

OptionTypeDefaultDescription
eventsstring[]['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']Browser events to listen for
onClickfunctionnullClick handler over chart area
onHoverfunctionnullHover handler over chart area
options: {
  events: ['click'],  // Only respond to clicks
  onClick: (event, elements, chart) => {
    if (elements.length > 0) {
      const { datasetIndex, index } = elements[0];
      console.log(chart.data.datasets[datasetIndex].data[index]);
    }
  },
  onHover: (event, elements, chart) => {
    chart.canvas.style.cursor = elements.length ? 'pointer' : 'default';
  }
}

Convert Event to Data Values

onClick: (e) => {
  const position = Chart.helpers.getRelativePosition(e, chart);
  const dataX = chart.scales.x.getValueForPixel(position.x);
  const dataY = chart.scales.y.getValueForPixel(position.y);
}

Layout Configuration

Namespace: options.layout

layout: {
  padding: { top: 20, right: 20, bottom: 20, left: 20 },
  autoPadding: true  // Auto-adjust for labels
}

Font Configuration

Global defaults:

Chart.defaults.font.family = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
Chart.defaults.font.size = 12;
Chart.defaults.font.weight = 'normal';
Chart.defaults.font.lineHeight = 1.2;
Chart.defaults.color = '#666';

Per-element font:

font: { family: 'Arial', size: 18, weight: 'bold', style: 'italic', lineHeight: 1.2 }

Color Configuration

Supported formats: named ('red'), hex ('#ff0000'), RGB ('rgb(255,0,0)'), RGBA ('rgba(255,0,0,0.5)'), HSL ('hsl(0,100%,50%)'), HSLA.

Global color defaults:

Chart.defaults.backgroundColor = 'rgba(0, 0, 0, 0.1)';
Chart.defaults.borderColor = 'rgba(0, 0, 0, 0.1)';
Chart.defaults.color = '#666';

Element Configuration

Default styles for chart elements:

// Points (line, radar, scatter)
Chart.defaults.elements.point.radius = 3;
Chart.defaults.elements.point.hoverRadius = 4;

// Lines
Chart.defaults.elements.line.tension = 0;
Chart.defaults.elements.line.borderWidth = 3;

// Bars
Chart.defaults.elements.bar.borderWidth = 0;
Chart.defaults.elements.bar.borderRadius = 0;

// Arcs (pie, doughnut, polar)
Chart.defaults.elements.arc.borderWidth = 2;

Global Defaults

Chart.defaults.responsive = true;
Chart.defaults.maintainAspectRatio = true;
Chart.defaults.interaction.mode = 'nearest';
Chart.defaults.plugins.legend.position = 'bottom';
Chart.defaults.datasets.line.tension = 0.4;

Additional Configuration

Other configuration topics not covered in detail here:

  • Decimation: Reduce data points for large datasets (options.plugins.decimation)
  • Locale: Number/date formatting (options.locale)
  • Device Pixel Ratio: Canvas resolution (options.devicePixelRatio)
  • Canvas Background: Background color plugin for exports

References

  • references/advanced-animations.md - Transitions, callbacks, animation object
  • references/tooltip-customization.md - External tooltips, Tooltip Model, custom positioners
  • references/legend-customization.md - Legend Item Interface, custom handlers

Examples

  • examples/responsive-chart.html - Proper container setup, flexbox, print handling
  • examples/custom-tooltip.html - External HTML tooltip implementation
  • examples/interactive-legend.html - Custom legend click behavior

Source

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

Overview

A practical guide to configuring Chart.js v4.5.1 options, animations, legends, tooltips, and interactions. It covers the core configuration structure, responsive behavior, and how to tailor fonts, colors, layout, and padding using the options and plugins. Use the examples to implement precise visuals and user interactions in charts.

How This Skill Works

You define a config object with type, data, and an options block that includes responsive, aspectRatio, events, onClick, onHover, and a plugins area for legend, tooltip, and title. The profile of each feature (legend, tooltip, layout, animation, interaction) is exposed under options and options.plugins, allowing precise customization. The skill demonstrates how to wire these options to achieve custom visuals, behavior, and responsive charts in v4.5.1.

When to Use It

  • When you want to configure Chart.js options, plugins, and styling for v4.5.1 charts.
  • When you need to customize legends, tooltips, titles, and their behavior and appearance.
  • When you require precise control over animations, transitions, and user interactions (hover, click).
  • When building responsive charts and tuning aspectRatio, layout, and padding across containers.
  • When implementing custom legends or external tooltips via plugins.

Quick Start

  1. Step 1: Create a config object with type, data, and an options block (including plugins).
  2. Step 2: Customize options.plugins.legend, options.plugins.tooltip, and layout/animation as needed.
  3. Step 3: Initialize Chart with the canvas context and the config object.

Best Practices

  • Use a single config object with a clear separation: data, options, and plugins.
  • Enable responsive once and adjust aspectRatio and maintainAspectRatio for layouts.
  • Quota and test event handlers (onClick, onHover) to avoid conflicting interactions.
  • Leverage options.plugins.legend and options.plugins.tooltip for targeted styling and behavior.
  • Validate color, font, and padding settings to maintain accessibility and readability.

Example Use Cases

  • Responsive line chart with custom tooltip formatting and a centered legend.
  • Bar chart with a customized legend (box size, padding) and a dark theme.
  • Pie/doughnut chart using an external tooltip plugin for advanced positioning.
  • Chart with disabled initial animation to highlight data on load.
  • Chart grid with tailored layout padding and font settings across devices.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers