This is a sophisticated technical request. Let me design a complete, polished charting framework with:
Let me create this comprehensive framework with a stunning demo page.
A high-performance charting framework with automatic SVG/Canvas switching based on data density, built with D3.js and ResizeObserver.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spectrum Charts Framework</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://d3js.org/d3.v7.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0a0a0f;
--bg-elevated: #12121a;
--bg-card: #1a1a24;
--fg: #e8e8ed;
--fg-muted: #6b6b7a;
--accent: #00d4aa;
--accent-dim: rgba(0, 212, 170, 0.15);
--border: #2a2a3a;
--chart-1: #00d4aa;
--chart-2: #ff6b9d;
--chart-3: #ffd93d;
--chart-4: #6b8aff;
--chart-5: #ff8c42;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Space Grotesk', sans-serif;
background: var(--bg);
color: var(--fg);
min-height: 100vh;
overflow-x: hidden;
}
.font-mono {
font-family: 'JetBrains Mono', monospace;
}
/* Background texture */
.bg-texture {
background-image:
radial-gradient(ellipse 80% 50% at 50% -20%, rgba(0, 212, 170, 0.08), transparent),
radial-gradient(ellipse 60% 40% at 80% 100%, rgba(107, 138, 255, 0.06), transparent),
url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.03'/%3E%3C/svg%3E");
}
/* Chart container */
.chart-container {
position: relative;
width: 100%;
height: 100%;
min-height: 200px;
}
.chart-container canvas,
.chart-container svg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* Tooltip */
.chart-tooltip {
position: fixed;
pointer-events: none;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 8px;
padding: 10px 14px;
font-size: 13px;
box-shadow: 0 10px 40px rgba(0,0,0,0.4);
z-index: 1000;
opacity: 0;
transform: translateY(4px);
transition: opacity 0.15s, transform 0.15s;
}
.chart-tooltip.visible {
opacity: 1;
transform: translateY(0);
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--fg-muted);
}
/* Animations */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.animate-in {
animation: fadeInUp 0.6s ease-out forwards;
}
.stagger-1 { animation-delay: 0.1s; }
.stagger-2 { animation-delay: 0.2s; }
.stagger-3 { animation-delay: 0.3s; }
.stagger-4 { animation-delay: 0.4s; }
@media (prefers-reduced-motion: reduce) {
.animate-in {
animation: none;
opacity: 1;
}
}
/* Button styles */
.btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 18px;
border-radius: 8px;
font-weight: 500;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
border: 1px solid transparent;
}
.btn-primary {
background: var(--accent);
color: var(--bg);
}
.btn-primary:hover {
filter: brightness(1.1);
transform: translateY(-1px);
}
.btn-secondary {
background: var(--bg-card);
color: var(--fg);
border-color: var(--border);
}
.btn-secondary:hover {
border-color: var(--accent);
background: var(--bg-elevated);
}
.btn-secondary.active {
border-color: var(--accent);
background: var(--accent-dim);
color: var(--accent);
}
/* Range slider */
input[type="range"] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 6px;
background: var(--border);
border-radius: 3px;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
background: var(--accent);
border-radius: 50%;
cursor: pointer;
transition: transform 0.15s;
}
input[type="range"]::-webkit-slider-thumb:hover {
transform: scale(1.2);
}
/* Legend */
.legend-item {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
transition: background 0.2s;
}
.legend-item:hover {
background: var(--bg-elevated);
}
.legend-dot {
width: 10px;
height: 10px;
border-radius: 50%;
}
/* Performance badge */
.perf-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: 20px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.perf-badge.svg-mode {
background: rgba(107, 138, 255, 0.15);
color: #6b8aff;
}
.perf-badge.canvas-mode {
background: rgba(255, 107, 157, 0.15);
color: #ff6b9d;
}
.perf-badge .dot {
width: 6px;
height: 6px;
border-radius: 50%;
animation: pulse 1.5s ease-in-out infinite;
}
</style>
</head>
<body class="bg-texture">
<!-- Header -->
<header class="border-b border-[var(--border)] sticky top-0 z-50 backdrop-blur-xl bg-[var(--bg)]/80">
<div class="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-lg bg-gradient-to-br from-[var(--accent)] to-[#6b8aff] flex items-center justify-center">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" class="text-[var(--bg)]">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline>
</svg>
</div>
<div>
<h1 class="text-lg font-semibold tracking-tight">Spectrum Charts</h1>
<p class="text-xs text-[var(--fg-muted)]">Responsive D3 Framework</p>
</div>
</div>
<div class="flex items-center gap-4">
<span class="perf-badge svg-mode" id="modeIndicator">
<span class="dot"></span>
<span class="label">SVG Mode</span>
</span>
<a href="#" class="text-[var(--fg-muted)] hover:text-[var(--fg)] transition-colors">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"></path>
</svg>
</a>
</div>
</div>
</header>
<main class="max-w-7xl mx-auto px-6 py-10">
<!-- Controls -->
<section class="mb-10 animate-in opacity-0">
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl p-6">
<div class="flex flex-wrap items-start justify-between gap-6">
<div>
<h2 class="text-xl font-semibold mb-1">Configuration</h2>
<p class="text-sm text-[var(--fg-muted)]">Adjust parameters to see automatic rendering optimization</p>
</div>
<div class="flex flex-wrap gap-3">
<button class="btn btn-secondary active" data-chart-type="line">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline>
</svg>
Line
</button>
<button class="btn btn-secondary" data-chart-type="area">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"></path>
</svg>
Area
</button>
<button class="btn btn-secondary" data-chart-type="bar">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="12" width="4" height="9"></rect>
<rect x="10" y="8" width="4" height="13"></rect>
<rect x="17" y="4" width="4" height="17"></rect>
</svg>
Bar
</button>
<button class="btn btn-secondary" data-chart-type="scatter">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="7" cy="15" r="2"></circle>
<circle cx="17" cy="7" r="2"></circle>
<circle cx="12" cy="12" r="2"></circle>
</svg>
Scatter
</button>
</div>
</div>
<div class="mt-6 grid md:grid-cols-2 gap-6">
<div>
<label class="flex items-center justify-between mb-3">
<span class="text-sm font-medium">Data Points</span>
<span class="font-mono text-sm text-[var(--accent)]" id="dataPointsValue">500</span>
</label>
<input type="range" id="dataPoints" min="50" max="10000" value="500" step="50">
<div class="flex justify-between text-xs text-[var(--fg-muted)] mt-1">
<span>50 (SVG)</span>
<span>10000 (Canvas)</span>
</div>
</div>
<div>
<label class="flex items-center justify-between mb-3">
<span class="text-sm font-medium">Canvas Threshold</span>
<span class="font-mono text-sm text-[var(--accent)]" id="thresholdValue">1000</span>
</label>
<input type="range" id="canvasThreshold" min="100" max="5000" value="1000" step="100">
<p class="text-xs text-[var(--fg-muted)] mt-1">Switches to Canvas when points exceed threshold</p>
</div>
</div>
<div class="mt-6 pt-6 border-t border-[var(--border)] flex flex-wrap gap-3">
<button class="btn btn-primary" id="regenerateBtn">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 2v6h-6M3 22v-6h6M21 12A9 9 0 0 0 6 6l-3 3M3 12a9 9 0 0 0 15 6l3-3"></path>
</svg>
Regenerate Data
</button>
<button class="btn btn-secondary" id="addSeriesBtn">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
Add Series
</button>
<button class="btn btn-secondary" id="clearSeriesBtn">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
Clear
</button>
</div>
</div>
</section>
<!-- Main Chart -->
<section class="mb-10 animate-in opacity-0 stagger-1">
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div class="px-6 py-4 border-b border-[var(--border)] flex items-center justify-between">
<div>
<h3 class="font-semibold">Real-time Performance Metrics</h3>
<p class="text-sm text-[var(--fg-muted)]">Automatic SVG/Canvas switching based on data density</p>
</div>
<div id="legend" class="flex gap-2"></div>
</div>
<div class="chart-container" id="mainChart" style="height: 400px;"></div>
</div>
</section>
<!-- Stats Row -->
<section class="grid md:grid-cols-4 gap-4 mb-10 animate-in opacity-0 stagger-2">
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl p-5">
<div class="text-sm text-[var(--fg-muted)] mb-1">Render Mode</div>
<div class="text-2xl font-bold text-[var(--accent)] font-mono" id="statMode">SVG</div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl p-5">
<div class="text-sm text-[var(--fg-muted)] mb-1">Total Points</div>
<div class="text-2xl font-bold font-mono" id="statPoints">0</div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl p-5">
<div class="text-sm text-[var(--fg-muted)] mb-1">Render Time</div>
<div class="text-2xl font-bold text-[var(--chart-2)] font-mono" id="statTime">0ms</div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl p-5">
<div class="text-sm text-[var(--fg-muted)] mb-1">FPS</div>
<div class="text-2xl font-bold text-[var(--chart-3)] font-mono" id="statFps">60</div>
</div>
</section>
<!-- Mini Charts Grid -->
<section class="animate-in opacity-0 stagger-3">
<h3 class="text-lg font-semibold mb-4">Multi-Chart Grid</h3>
<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div class="px-4 py-3 border-b border-[var(--border)]">
<span class="text-sm font-medium">CPU Usage</span>
</div>
<div class="chart-container mini-chart" data-series="1" style="height: 160px;"></div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div class="px-4 py-3 border-b border-[var(--border)]">
<span class="text-sm font-medium">Memory</span>
</div>
<div class="chart-container mini-chart" data-series="1" style="height: 160px;"></div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div class="px-4 py-3 border-b border-[var(--border)]">
<span class="text-sm font-medium">Network I/O</span>
</div>
<div class="chart-container mini-chart" data-series="2" style="height: 160px;"></div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div class="px-4 py-3 border-b border-[var(--border)]">
<span class="text-sm font-medium">Disk Activity</span>
</div>
<div class="chart-container mini-chart" data-series="1" style="height: 160px;"></div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div class="px-4 py-3 border-b border-[var(--border)]">
<span class="text-sm font-medium">Request Rate</span>
</div>
<div class="chart-container mini-chart" data-series="2" style="height: 160px;"></div>
</div>
<div class="bg-[var(--bg-card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div class="px-4 py-3 border-b border-[var(--border)]">
<span class="text-sm font-medium">Error Rate</span>
</div>
<div class="chart-container mini-chart" data-series="1" style="height: 160px;"></div>
</div>
</div>
</section>
</main>
<!-- Tooltip -->
<div class="chart-tooltip" id="tooltip"></div>
<script>
// =========================================
// SPECTRUM CHARTS FRAMEWORK
// =========================================
const SpectrumCharts = (function() {
// Color palette
const COLORS = ['#00d4aa', '#ff6b9d', '#ffd93d', '#6b8aff', '#ff8c42'];
// Default configuration
const DEFAULT_CONFIG = {
margin: { top: 20, right: 30, bottom: 40, left: 50 },
canvasThreshold: 1000,
transitionDuration: 300,
gridLines: true,
animate: true,
responsive: true,
tooltip: true,
xAxis: true,
yAxis: true,
smooth: true
};
// Check reduced motion preference
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// =========================================
// CHART CLASS
// =========================================
class Chart {
constructor(container, options = {}) {
this.container = typeof container === 'string'
? document.querySelector(container)
: container;
if (!this.container) {
throw new Error('Container element not found');
}
this.config = { ...DEFAULT_CONFIG, ...options };
this.config.margin = { ...DEFAULT_CONFIG.margin, ...(options.margin || {}) };
this.data = [];
this.series = [];
this.svg = null;
this.canvas = null;
this.ctx = null;
this.scales = {};
this.isCanvas = false;
this.resizeObserver = null;
this.animationFrame = null;
this.hoveredPoint = null;
this.init();
}
init() {
// Create SVG element
this.svg = d3.select(this.container)
.append('svg')
.attr('class', 'chart-svg')
.style('position', 'absolute')
.style('top', 0)
.style('left', 0)
.style('width', '100%')
.style('height', '100%');
// Create canvas element
this.canvas = d3.select(this.container)
.append('canvas')
.attr('class', 'chart-canvas')
.style('position', 'absolute')
.style('top', 0)
.style('left', 0)
.style('width', '100%')
.style('height', '100%')
.style('opacity', 0)
.style('pointer-events', 'none');
this.ctx = this.canvas.node().getContext('2d');
// Create main group
this.g = this.svg.append('g').attr('class', 'chart-main');
// Create layers
this.gridGroup = this.g.append('g').attr('class', 'chart-grid');
this.axesGroup = this.g.append('g').attr('class', 'chart-axes');
this.dataGroup = this.g.append('g').attr('class', 'chart-data');
this.interactionGroup = this.g.append('g').attr('class', 'chart-interaction');
// Setup resize observer
if (this.config.responsive) {
this.setupResizeObserver();
}
// Initial render
this.updateDimensions();
}
setupResizeObserver() {
this.resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
if (entry.contentRect.width > 0 && entry.contentRect.height > 0) {
this.onResize();
}
}
});
this.resizeObserver.observe(this.container);
}
onResize() {
if (this.animationFrame) {
cancelAnimationFrame(this.animationFrame);
}
this.animationFrame = requestAnimationFrame(() => {
this.updateDimensions();
this.render(false);
});
}
updateDimensions() {
const rect = this.container.getBoundingClientRect();
this.width = rect.width;
this.height = rect.height;
// Set canvas resolution for high DPI
const dpr = window.devicePixelRatio || 1;
this.canvas
.attr('width', this.width * dpr)
.attr('height', this.height * dpr);
this.ctx.scale(dpr, dpr);
// Update main group position
this.g.attr(
'transform',
`translate(${this.config.margin.left}, ${this.config.margin.top})`
);
// Calculate inner dimensions
this.innerWidth = Math.max(1, this.width - this.config.margin.left - this.config.margin.right);
this.innerHeight = Math.max(1, this.height - this.config.margin.top - this.config.margin.bottom);
}
setData(data, series = null) {
this.data = data;
if (series) {
this.series = series;
}
return this;
}
addSeries(name, color = null) {
const seriesColor = color || COLORS[this.series.length % COLORS.length];
this.series.push({ name, color: seriesColor, data: [] });
return this;
}
setSeriesData(index, data) {
if (this.series[index]) {
this.series[index].data = data;
}
return this;
}
generateRandomData(points, seriesCount = 1) {
this.series = [];
this.data = [];
for (let s = 0; s < seriesCount; s++) {
const seriesData = [];
let value = 50 + Math.random() * 30;
for (let i = 0; i < points; i++) {
value += (Math.random() - 0.5) * 10;
value = Math.max(0, Math.min(100, value));
seriesData.push({
x: i,
y: value,
series: s
});
}
if (s === 0) {
this.data = seriesData;
}
this.series.push({
name: `Series ${s + 1}`,
color: COLORS[s % COLORS.length],
data: seriesData
});
}
return this;
}
setChartType(type) {
this.config.type = type;
return this;
}
setCanvasThreshold(threshold) {
this.config.canvasThreshold = threshold;
return this;
}
shouldUseCanvas() {
const totalPoints = this.series.reduce((sum, s) => sum + s.data.length, 0) || this.data.length;
return totalPoints > this.config.canvasThreshold;
}
render(animate = true) {
const startTime = performance.now();
// Determine render mode
this.isCanvas = this.shouldUseCanvas();
// Update visibility
this.svg.style('opacity', this.isCanvas ? 0 : 1);
this.canvas.style('opacity', this.isCanvas ? 1 : 0);
// Setup scales
this.setupScales();
if (this.isCanvas) {
this.renderCanvas();
} else {
this.renderSVG(animate);
}
// Always render axes in SVG
this.renderAxes();
this.renderGrid();
const renderTime = performance.now() - startTime;
this.updateStats(renderTime);
return this;
}
setupScales() {
// X scale
const allX = this.series.length > 0
? this.series.flatMap(s => s.data.map(d => d.x))
: this.data.map(d => d.x);
this.scales.x = d3.scaleLinear()
.domain(d3.extent(allX))
.range([0, this.innerWidth]);
// Y scale
const allY = this.series.length > 0
? this.series.flatMap(s => s.data.map(d => d.y))
: this.data.map(d => d.y);
this.scales.y = d3.scaleLinear()
.domain([0, d3.max(allY) * 1.1])
.range([this.innerHeight, 0]);
// Color scale
this.scales.color = d3.scaleOrdinal()
.domain(this.series.map((_, i) => i))
.range(COLORS);
}
renderSVG(animate) {
const duration = (animate && !prefersReducedMotion)
? this.config.transitionDuration
: 0;
this.dataGroup.selectAll('*').remove();
const type = this.config.type || 'line';
this.series.forEach((series, seriesIndex) => {
const data = series.data;
if (type === 'line' || type === 'area') {
// Area
if (type === 'area') {
const area = d3.area()
.x(d => this.scales.x(d.x))
.y0(this.innerHeight)
.y1(d => this.scales.y(d.y))
.curve(this.config.smooth ? d3.curveMonotoneX : d3.curveLinear);
const areaPath = this.dataGroup
.append('path')
.attr('class', `area area-${seriesIndex}`)
.attr('d', area(data))
.attr('fill', series.color)
.attr('fill-opacity', 0.15);
if (duration > 0) {
areaPath
.attr('fill-opacity', 0)
.transition()
.duration(duration)
.attr('fill-opacity', 0.15);
}
}
// Line
const line = d3.line()
.x(d => this.scales.x(d.x))
.y(d => this.scales.y(d.y))
.curve(this.config.smooth ? d3.curveMonotoneX : d3.curveLinear);
const linePath = this.dataGroup
.append('path')
.attr('class', `line line-${seriesIndex}`)
.attr('d', line(data))
.attr('fill', 'none')
.attr('stroke', series.color)
.attr('stroke-width', 2)
.attr('stroke-linecap', 'round')
.attr('stroke-linejoin', 'round');
if (duration > 0) {
const pathLength = linePath.node().getTotalLength();
linePath
.attr('stroke-dasharray', pathLength)
.attr('stroke-dashoffset', pathLength)
.transition()
.duration(duration * 2)
.ease(d3.easeQuadOut)
.attr('stroke-dashoffset', 0);
}
} else if (type === 'bar') {
const barWidth = Math.max(1, (this.innerWidth / data.length) * 0.8);
const bars = this.dataGroup
.selectAll(`.bar-${seriesIndex}`)
.data(data)
.join('rect')
.attr('class', `bar bar-${seriesIndex}`)
.attr('x', d => this.scales.x(d.x) - barWidth / 2)
.attr('width', barWidth)
.attr('fill', series.color)
.attr('rx', 2);
if (duration > 0) {
bars
.attr('y', this.innerHeight)
.attr('height', 0)
.transition()
.duration(duration)
.delay((_, i) => i * (duration / data.length) * 0.5)
.attr('y', d => this.scales.y(d.y))
.attr('height', d => this.innerHeight - this.scales.y(d.y));
} else {
bars
.attr('y', d => this.scales.y(d.y))
.attr('height', d => this.innerHeight - this.scales.y(d.y));
}
} else if (type === 'scatter') {
const circles = this.dataGroup
.selectAll(`.point-${seriesIndex}`)
.data(data)
.join('circle')
.attr('class', `point point-${seriesIndex}`)
.attr('cx', d => this.scales.x(d.x))
.attr('cy', d => this.scales.y(d.y))
.attr('r', 4)
.attr('fill', series.color)
.attr('stroke', 'rgba(10, 10, 15, 0.5)')
.attr('stroke-width', 1);
if (duration > 0) {
circles
.attr('r', 0)
.attr('opacity', 0)
.transition()
.duration(duration)
.delay((_, i) => i * (duration / data.length) * 0.3)
.attr('r', 4)
.attr('opacity', 1);
}
}
});
// Interaction overlay
this.setupInteraction();
}
renderCanvas() {
const ctx = this.ctx;
const dpr = window.devicePixelRatio || 1;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, this.width, this.height);
ctx.save();
ctx.translate(this.config.margin.left, this.config.margin.top);
const type = this.config.type || 'line';
this.series.forEach((series, seriesIndex) => {
const data = series.data;
const color = series.color;
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
if (type === 'line' || type === 'area') {
ctx.beginPath();
data.forEach((d, i) => {
const x = this.scales.x(d.x);
const y = this.scales.y(d.y);
if (i === 0) {
ctx.moveTo(x, y);
} else {
if (this.config.smooth && i > 0) {
const prev = data[i - 1];
const px = this.scales.x(prev.x);
const py = this.scales.y(prev.y);
const cpx = (px + x) / 2;
ctx.quadraticCurveTo(px, py, cpx, (py + y) / 2);
} else {
ctx.lineTo(x, y);
}
}
});
if (type === 'area') {
ctx.lineTo(this.innerWidth, this.innerHeight);
ctx.lineTo(0, this.innerHeight);
ctx.closePath();
ctx.globalAlpha = 0.15;
ctx.fill();
ctx.globalAlpha = 1;
}
ctx.stroke();
} else if (type === 'bar') {
const barWidth = Math.max(1, (this.innerWidth / data.length) * 0.8);
ctx.globalAlpha = 0.85;
data.forEach(d => {
const x = this.scales.x(d.x) - barWidth / 2;
const y = this.scales.y(d.y);
const h = this.innerHeight - y;
ctx.beginPath();
ctx.roundRect(x, y, barWidth, h, 2);
ctx.fill();
});
ctx.globalAlpha = 1;
} else if (type === 'scatter') {
ctx.globalAlpha = 0.8;
data.forEach(d => {
const x = this.scales.x(d.x);
const y = this.scales.y(d.y);
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
});
ctx.globalAlpha = 1;
}
});
ctx.restore();
}
renderAxes() {
this.axesGroup.selectAll('*').remove();
// X Axis
if (this.config.xAxis) {
const xAxis = d3.axisBottom(this.scales.x)
.ticks(6)
.tickSize(0);
this.axesGroup
.append('g')
.attr('class', 'x-axis')
.attr('transform', `translate(0, ${this.innerHeight})`)
.call(xAxis)
.call(g => g.select('.domain').attr('stroke', '#2a2a3a'))
.call(g => g.selectAll('text')
.attr('fill', '#6b6b7a')
.attr('font-size', '11px')
.attr('font-family', 'JetBrains Mono'));
}
// Y Axis
if (this.config.yAxis) {
const yAxis = d3.axisLeft(this.scales.y)
.ticks(5)
.tickSize(0);
this.axesGroup
.append('g')
.attr('class', 'y-axis')
.call(yAxis)
.call(g => g.select('.domain').remove())
.call(g => g.selectAll('text')
.attr('fill', '#6b6b7a')
.attr('font-size', '11px')
.attr('font-family', 'JetBrains Mono'));
}
}
renderGrid() {
this.gridGroup.selectAll('*').remove();
if (!this.config.gridLines) return;
// Horizontal grid lines
const yTicks = this.scales.y.ticks(5);
this.gridGroup
.selectAll('.grid-h')
.data(yTicks)
.join('line')
.attr('class', 'grid-h')
.attr('x1', 0)
.attr('x2', this.innerWidth)
.attr('y1', d => this.scales.y(d))
.attr('y2', d => this.scales.y(d))
.attr('stroke', '#2a2a3a')
.attr('stroke-dasharray', '3,3')
.attr('opacity', 0.5);
}
setupInteraction() {
this.interactionGroup.selectAll('*').remove();
if (!this.config.tooltip || this.isCanvas) return;
// Invisible overlay for mouse tracking
const bisect = d3.bisector(d => d.x).left;
const overlay = this.interactionGroup
.append('rect')
.attr('width', this.innerWidth)
.attr('height', this.innerHeight)
.attr('fill', 'transparent')
.style('cursor', 'crosshair');
// Vertical line indicator
const verticalLine = this.interactionGroup
.append('line')
.attr('class', 'indicator-line')
.attr('y1', 0)
.attr('y2', this.innerHeight)
.attr('stroke', 'rgba(0, 212, 170, 0.5)')
.attr('stroke-width', 1)
.attr('stroke-dasharray', '4,4')
.style('opacity', 0);
// Highlight circles
const highlightCircles = this.interactionGroup
.append('g')
.attr('class', 'highlight-circles');
this.series.forEach((series, i) => {
highlightCircles
.append('circle')
.attr('class', `highlight-${i}`)
.attr('r', 6)
.attr('fill', 'transparent')
.attr('stroke', series.color)
.attr('stroke-width', 2)
.style('opacity', 0);
});
const tooltip = document.getElementById('tooltip');
overlay
.on('mousemove', (event) => {
const [mx] = d3.pointer(event);
const x0 = this.scales.x.invert(mx);
verticalLine
.attr('x1', mx)
.attr('x2', mx)
.style('opacity', 1);
let tooltipContent = '';
this.series.forEach((series, i) => {
const data = series.data;
const idx = bisect(data, x0, 1);
const d0 = data[idx - 1];
const d1 = data[idx];
const d = d1 && (x0 - d0.x > d1.x - x0) ? d1 : d0;
if (d) {
const cx = this.scales.x(d.x);
const cy = this.scales.y(d.y);
highlightCircles
.select(`.highlight-${i}`)
.attr('cx', cx)
.attr('cy', cy)
.style('opacity', 1);
tooltipContent += `
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
<span style="width: 8px; height: 8px; border-radius: 50%; background: ${series.color};"></span>
<span style="color: #e8e8ed; font-weight: 500;">${series.name}</span>
<span style="color: #6b6b7a; margin-left: auto;">${d.y.toFixed(1)}</span>
</div>
`;
}
});
if (tooltip && tooltipContent) {
tooltip.innerHTML = tooltipContent;
tooltip.classList.add('visible');
const tooltipRect = tooltip.getBoundingClientRect();
const containerRect = this.container.getBoundingClientRect();
let left = event.clientX + 15;
let top = event.clientY - 10;
if (left + tooltipRect.width > window.innerWidth - 20) {
left = event.clientX - tooltipRect.width - 15;
}
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
}
})
.on('mouseleave', () => {
verticalLine.style('opacity', 0);
highlightCircles.selectAll('circle').style('opacity', 0);
if (tooltip) {
tooltip.classList.remove('visible');
}
});
}
updateStats(renderTime) {
const totalPoints = this.series.reduce((sum, s) => sum + s.data.length, 0);
document.getElementById('statMode').textContent = this.isCanvas ? 'Canvas' : 'SVG';
document.getElementById('statPoints').textContent = totalPoints.toLocaleString();
document.getElementById('statTime').textContent = `${renderTime.toFixed(1)}ms`;
const modeIndicator = document.getElementById('modeIndicator');
if (this.isCanvas) {
modeIndicator.className = 'perf-badge canvas-mode';
modeIndicator.querySelector('.label').textContent = 'Canvas Mode';
} else {
modeIndicator.className = 'perf-badge svg-mode';
modeIndicator.querySelector('.label').textContent = 'SVG Mode';
}
}
destroy() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
}
if (this.animationFrame) {
cancelAnimationFrame(this.animationFrame);
}
d3.select(this.container).selectAll('*').remove();
}
}
// =========================================
// FACTORY FUNCTIONS
// =========================================
function createChart(container, options = {}) {
return new Chart(container, options);
}
function generateTimeSeriesData(points, series = 1, options = {}) {
const { startValue = 50, volatility = 10, trend = 0 } = options;
const data = [];
for (let s = 0; s < series; s++) {
const seriesData = [];
let value = startValue + Math.random() * 20;
for (let i = 0; i < points; i++) {
value += (Math.random() - 0.5) * volatility + trend;
value = Math.max(0, Math.min(100, value));
seriesData.push({ x: i, y: value, series: s });
}
data.push(seriesData);
}
return data;
}
return {
Chart,
createChart,
generateTimeSeriesData,
COLORS
};
})();
// =========================================
// APPLICATION
// =========================================
// Initialize main chart
let mainChart = null;
let miniCharts = [];
let currentType = 'line';
let dataPoints = 500;
let canvasThreshold = 1000;
let seriesCount = 2;
function initMainChart() {
const container = document.getElementById('mainChart');
if (mainChart) {
mainChart.destroy();
}
mainChart = SpectrumCharts.createChart(container, {
type: currentType,
canvasThreshold: canvasThreshold,
smooth: true
});
mainChart.generateRandomData(dataPoints, seriesCount);
updateLegend();
mainChart.render();
}
function initMiniCharts() {
miniCharts.forEach(chart => chart.destroy());
miniCharts = [];
document.querySelectorAll('.mini-chart').forEach((container, i) => {
const seriesNum = parseInt(container.dataset.series) || 1;
const types = ['line', 'area', 'bar', 'scatter'];
const chart = SpectrumCharts.createChart(container, {
type: types[i % types.length],
canvasThreshold: 500,
margin: { top: 10, right: 10, bottom: 20, left: 30 },
gridLines: false
});
chart.generateRandomData(100 + Math.floor(Math.random() * 200), seriesNum);
chart.render();
miniCharts.push(chart);
});
}
function updateLegend() {
const legend = document.getElementById('legend');
legend.innerHTML = '';
mainChart.series.forEach((series, i) => {
const item = document.createElement('div');
item.className = 'legend-item';
item.innerHTML = `
<span class="legend-dot" style="background: ${series.color}"></span>
<span class="text-sm">${series.name}</span>
`;
legend.appendChild(item);
});
}
// Event handlers
document.querySelectorAll('[data-chart-type]').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('[data-chart-type]').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentType = btn.dataset.chartType;
mainChart.setChartType(currentType).render();
});
});
document.getElementById('dataPoints').addEventListener('input', (e) => {
dataPoints = parseInt(e.target.value);
document.getElementById('dataPointsValue').textContent = dataPoints;
});
document.getElementById('dataPoints').addEventListener('change', () => {
mainChart.generateRandomData(dataPoints, seriesCount);
mainChart.render();
});
document.getElementById('canvasThreshold').addEventListener('input', (e) => {
canvasThreshold = parseInt(e.target.value);
document.getElementById('thresholdValue').textContent = canvasThreshold;
});
document.getElementById('canvasThreshold').addEventListener('change', () => {
mainChart.setCanvasThreshold(canvasThreshold).render();
});
document.getElementById('regenerateBtn').addEventListener('click', () => {
mainChart.generateRandomData(dataPoints, seriesCount);
updateLegend();
mainChart.render();
});
document.getElementById('addSeriesBtn').addEventListener('click', () => {
if (seriesCount < 5) {
seriesCount++;
mainChart.generateRandomData(dataPoints, seriesCount);
updateLegend();
mainChart.render();
}
});
document.getElementById('clearSeriesBtn').addEventListener('click', () => {
seriesCount = 1;
mainChart.generateRandomData(dataPoints, seriesCount);
updateLegend();
mainChart.render();
});
// FPS counter
let lastTime = performance.now();
let frameCount = 0;
function updateFPS() {
frameCount++;
const now = performance.now();
if (now - lastTime >= 1000) {
document.getElementById('statFps').textContent = frameCount;
frameCount = 0;
lastTime = now;
}
requestAnimationFrame(updateFPS);
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
initMainChart();
initMiniCharts();
updateFPS();
});
// Handle window resize for mini charts
window.addEventListener('resize', () => {
miniCharts.forEach(chart => {
if (chart.resizeObserver) {
chart.onResize();
}
});
});
</script>
</body>
</html>