Add PNG export for charts
- Hover any chart to reveal download button - Exports with white background and padding - Works on Dashboard and Comparison pages
This commit is contained in:
57
src/components/ChartExport.js
Normal file
57
src/components/ChartExport.js
Normal file
@@ -0,0 +1,57 @@
|
||||
import React, { useRef } from 'react';
|
||||
|
||||
// Wrapper component that adds PNG export to any chart
|
||||
export function ExportableChart({ children, filename = 'chart', className = '' }) {
|
||||
const chartRef = useRef(null);
|
||||
|
||||
const exportAsPNG = () => {
|
||||
const chartContainer = chartRef.current;
|
||||
if (!chartContainer) return;
|
||||
|
||||
const canvas = chartContainer.querySelector('canvas');
|
||||
if (!canvas) return;
|
||||
|
||||
// Create a new canvas with white background
|
||||
const exportCanvas = document.createElement('canvas');
|
||||
const ctx = exportCanvas.getContext('2d');
|
||||
|
||||
// Set dimensions with padding
|
||||
const padding = 20;
|
||||
exportCanvas.width = canvas.width + (padding * 2);
|
||||
exportCanvas.height = canvas.height + (padding * 2);
|
||||
|
||||
// Fill white background
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.fillRect(0, 0, exportCanvas.width, exportCanvas.height);
|
||||
|
||||
// Draw the chart
|
||||
ctx.drawImage(canvas, padding, padding);
|
||||
|
||||
// Export
|
||||
const link = document.createElement('a');
|
||||
link.download = `${filename}-${new Date().toISOString().split('T')[0]}.png`;
|
||||
link.href = exportCanvas.toDataURL('image/png', 1.0);
|
||||
link.click();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`exportable-chart ${className}`}>
|
||||
<button
|
||||
className="chart-export-btn"
|
||||
onClick={exportAsPNG}
|
||||
title="Download as PNG"
|
||||
>
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
||||
<polyline points="7 10 12 15 17 10"/>
|
||||
<line x1="12" y1="15" x2="12" y2="3"/>
|
||||
</svg>
|
||||
</button>
|
||||
<div ref={chartRef} className="chart-canvas-wrapper">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ExportableChart;
|
||||
Reference in New Issue
Block a user