xiaohongshu
xiaohongshu
chartjs-overview
This skill should be used when the user asks "how to install Chart.js", "Chart.js setup", "getting started with Chart.js", "Chart.js CDN", "Chart.js npm install", "tree-shaking Chart.js", "Chart.js bundle optimization", "import Chart.js", "Chart.js module loaders", "Chart.js CommonJS", "Chart.js ...
Full skill instructions
Guidance for installing, configuring, and optimizing Chart.js v4.5.1 in web applications.
Install Chart.js via npm:
npm install chart.js
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>
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:
<canvas> element with an id<div> for responsive sizingnew Chart(ctx, config) with type, data, and optionsImport 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.
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.
Use dynamic import in CommonJS modules:
const { Chart } = await import('chart.js');
Require the UMD build:
require(['path/to/chartjs/dist/chart.umd.min.js'], function(Chart) {
const myChart = new Chart(ctx, { /* ... */ });
});
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.
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);
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.
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.
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.
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.
Reference Documentation:
references/tree-shaking.md - Complete component registration guide for all chart typesreferences/instance-methods.md - Chart instance methods, animation modes, and patternsreferences/configuration-patterns.md - Global defaults, helpers, responsive patternsWorking 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 updatesexamples/production-bundle.html - Tree-shaken builds with ESM importsxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience