npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

Readme

OK-CANVAS-EXPORT

Export complete SVG diagrams and canvases as high-quality PNG or SVG files, including content outside the visible viewport.

npm version License: MIT

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-export

npm

npm install ok-canvas-export

pnpm

pnpm add ok-canvas-export

Yarn

yarn add ok-canvas-export

Quick 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:

  • white
  • transparent
  • 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.

  1. Enables full render mode
  2. Waits for the complete diagram to render
  3. Calculates the real graphical bounds of the SVG
  4. Creates an independent SVG clone
  5. Removes artificial canvas backgrounds
  6. Applies the requested background
  7. Creates a viewBox covering the complete diagram
  8. Resolves CSS custom properties
  9. Serializes the SVG
  10. Converts the SVG to a high-quality PNG when requested
  11. Downloads the generated file
  12. 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.