ok-canvas-export
v1.1.1
Published
Export complete SVG diagrams and canvases as high-quality images with full render pass to bypass viewport culling
Maintainers
Readme
OK-CANVAS-EXPORT
Export complete SVG diagrams and canvases as high-quality PNG or SVG files, including content outside the visible viewport.
Features
- Export diagrams as PNG or SVG
- Export complete SVG content, even when parts are outside the visible viewport
- High-quality PNG rendering with configurable scale
- Configurable export margin
- Custom background colors
- Transparent background support
- Automatic CSS custom property resolution
- TypeScript support
- React hook for simple integration
- Works with Vite, Next.js, Create React App, react-scripts, Bun, npm, pnpm and Yarn
- Zero runtime dependencies except React
Installation
Bun
bun add ok-canvas-exportnpm
npm install ok-canvas-exportpnpm
pnpm add ok-canvas-exportYarn
yarn add ok-canvas-exportQuick Start
import { useRef } from 'react';
import { useDiagramExport } from 'ok-canvas-export';
const MyDiagram = () => {
const svgRef = useRef<SVGSVGElement>(null);
const {
exportDiagram,
isExporting,
exportAllTables,
} = useDiagramExport({
svgRef,
diagramData,
getTableHeight,
projectName: 'my-project',
});
const handleExport = async () => {
await exportDiagram({
format: 'png',
background: '#ffffff',
scale: 2,
margin: 100,
onProgress: (status) => {
console.log('Export status:', status);
},
});
};
return (
<>
<svg ref={svgRef}>
{/* Your diagram content */}
</svg>
<button
onClick={handleExport}
disabled={isExporting}
>
Export Diagram
</button>
</>
);
};Background Colors
The background option supports:
whitetransparent- Any valid CSS color string
Examples
background: '#C300FF'
background: '#1a1a1a'
background: 'rgb(30, 30, 30)'
background: 'hsl(260, 80%, 50%)'
background: 'rgba(0, 0, 0, 0.8)'
background: 'transparent'API
useDiagramExport
React hook that provides complete diagram export functionality.
Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| svgRef | React.RefObject<SVGSVGElement> | Yes | Reference to the SVG element that should be exported |
| diagramData | DiagramData | No | Optional diagram data used by the compatibility APIs |
| getTableHeight | GetTableHeight | No | Function that returns the height of a table |
| projectName | string | No | Project name used when generating the exported filename |
Returns
| Property | Type | Description |
|----------|------|-------------|
| isExporting | boolean | Boolean indicating whether an export is currently running |
| exportDiagram | Function | Function used to start an export |
| exportAllTables | boolean | Boolean indicating whether full rendering mode is enabled |
| setExportAllTables | Function | Function used to enable or disable full rendering mode |
exportDiagram
The core export function.
Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| format | 'png' \| 'svg' | 'png' | Defines the output format |
| background | string | 'white' | Defines the background color. Supports: white, transparent, or any valid CSS color |
| scale | number | 2 | Controls PNG rendering resolution |
| margin | number | 100 | Defines the space around the exported content |
| fileName | string | Auto-generated | Allows specifying a custom filename |
| onProgress | Function | - | Function called whenever the export process changes state |
PNG Export
PNG files are rendered through a canvas.
Example
await exportDiagram({
format: 'png',
background: '#ffffff',
scale: 3,
});Higher scale values generally produce larger and higher-resolution PNG files.
SVG Export
SVG exports preserve the SVG structure and use the calculated graphical bounds.
Example
await exportDiagram({
format: 'svg',
background: 'transparent',
});How It Works
The export process is designed to work with diagrams that use viewport culling or virtualization.
- Enables full render mode
- Waits for the complete diagram to render
- Calculates the real graphical bounds of the SVG
- Creates an independent SVG clone
- Removes artificial canvas backgrounds
- Applies the requested background
- Creates a viewBox covering the complete diagram
- Resolves CSS custom properties
- Serializes the SVG
- Converts the SVG to a high-quality PNG when requested
- Downloads the generated file
- Restores the original rendering state
The exporter does not depend on the visible SVG viewport or scroll container to determine the diagram size.
Viewport Culling
The library is especially useful for diagram editors that only render elements currently visible in the viewport.
Example
{tables.map((table) => {
if (!exportAllTables && !isVisible(table)) {
return null;
}
return <Table key={table.id} {...table} />;
})}During export, exportAllTables can be used to render the complete diagram before the SVG bounds are calculated.
TypeScript
The package includes TypeScript declarations.
Example
import {
useDiagramExport,
exportDiagram,
calculateSvgDimensions,
} from 'ok-canvas-export';Low-Level API
The package also exposes lower-level utilities.
| Function | Description |
|----------|-------------|
| calculateDimensions | Calculates dimensions from diagram data |
| calculateSvgDimensions | Calculates the real graphical bounds of an SVG |
| getSvgContentBounds | Returns the graphical bounds of an SVG |
| getScrollDimensions | Returns dimensions based on the SVG and its scroll container |
| renderHighQuality | Renders an SVG image into a high-resolution canvas |
| serializeSvg | Serializes an SVG element into SVG markup while resolving CSS custom properties |
| prepareSvgForExport | Creates a clean SVG clone configured for export |
| canvasToBlob | Converts a canvas into a Blob |
| downloadBlob | Downloads a Blob using a generated or custom filename |
| generateFileName | Generates a filename for exported files |
Diagram Data
The original diagram-data compatibility API expects tables with the following structure:
interface DiagramData {
tables: Array<{
id: string;
x: number;
y: number;
fields: any[];
}>;
relationships: any[];
}The diagramData and getTableHeight parameters are optional when using the exporter as a generic SVG exporter.
Browser Support
The library relies on browser APIs including:
- SVG
SVGElement.getBBox()- Canvas
- Blob
URL.createObjectURL()- Image
The library is intended to run in browser environments.
Framework Compatibility
The package is designed to work with standard React applications and common React build environments.
Supported environments include:
- Vite
- Next.js
- Create React App
- react-scripts
- Bun
- npm
- pnpm
- Yarn
The package provides both ESM and CommonJS builds to support modern bundlers as well as environments such as Create React App and react-scripts.
Requirements
- React >= 18
- Browser environment for performing exports
License
MIT
Contributing
Contributions, bug reports and pull requests are welcome.
If you find a problem or have an idea for improving the exporter, feel free to open an issue or submit a Pull Request.
