A modern TypeScript library to capture DOM elements as SVG, PNG, JPEG, or Blob images. Built with latest tooling and fully type-safe.
Forked & modified from dom-to-image
- πΈ Multiple Formats: SVG (vector), PNG (raster), JPEG (compressed), Blob, Pixel Data
- π¨ Style Preservation: Captures all CSS styles, colors, gradients, shadows, transforms
- π¦ Modern Build: Rollup with TypeScript, ESM and CommonJS outputs
- π Type Safe: Full TypeScript support with complete type definitions
- β‘ Fast: Optimized for performance, lazy initialization of dependencies
- π Production Ready: Tested and used in real-world applications
- π― React Friendly: Works seamlessly with React via refs
- π¬ Live Demo β Try it now! (no setup needed)
- Getting Started β See below or check
EXAMPLES_QUICKSTART.md - React Example β Run the interactive example in
examples/react-app/ - Testing β See
TESTING.mdfor test setup - Examples β Check
examples/README.mdfor detailed examples
| File | Purpose |
|---|---|
EXAMPLES_QUICKSTART.md |
Quick start guide for running examples |
TESTING.md |
Testing framework setup and usage |
TESTING_STATUS.md |
Current test status and results |
TEST_SETUP_SUMMARY.md |
Comprehensive testing documentation |
examples/README.md |
Examples overview |
examples/react-app/README.md |
Detailed React example guide |
tests/README.md |
Test infrastructure details |
Try it now! β dom-screenshot React Demo
Experience the library in action with an interactive React application. Capture UI elements as SVG, PNG, or JPEG with live preview! π
npm install @mkhuda/dom-screenshot
# or
yarn add @mkhuda/dom-screenshotimport { domtoimage } from '@mkhuda/dom-screenshot';
// Get the element to capture
const element = document.getElementById('content');
// Capture as SVG
const svg = await domtoimage.toSvg(element);
// Capture as PNG
const png = await domtoimage.toPng(element);
// Capture as JPEG
const jpeg = await domtoimage.toJpeg(element);
// Get as Blob
const blob = await domtoimage.toBlob(element);
// Get pixel data
const pixelData = await domtoimage.toPixelData(element);import { useRef } from 'react';
import { domtoimage } from '@mkhuda/dom-screenshot';
export function MyComponent() {
const contentRef = useRef<HTMLDivElement>(null);
const handleCapture = async () => {
if (!contentRef.current) return;
try {
const png = await domtoimage.toPng(contentRef.current);
// Download
const link = document.createElement('a');
link.href = png;
link.download = 'screenshot.png';
link.click();
} catch (error) {
console.error('Capture failed:', error);
}
};
return (
<div>
<div ref={contentRef}>
<h1>Content to capture</h1>
<p>This will be captured</p>
</div>
<button onClick={handleCapture}>πΈ Download as PNG</button>
</div>
);
}Renders DOM node to SVG data URL (scalable vector format).
Returns: Promise<string> - SVG data URL
Best for: UI components, diagrams, simple graphics
const svg = await domtoimage.toSvg(element);Renders DOM node to PNG data URL (lossless raster format).
Returns: Promise<string> - PNG data URL
Best for: Screenshots, general purpose captures
const png = await domtoimage.toPng(element);Renders DOM node to JPEG data URL (lossy compressed format).
Returns: Promise<string> - JPEG data URL
Best for: Photos, space-constrained scenarios
const jpeg = await domtoimage.toJpeg(element, { quality: 0.95 });Renders DOM node to Blob object.
Returns: Promise<Blob> - Blob object
Best for: Uploading to server, efficient data handling
const blob = await domtoimage.toBlob(element);Extracts raw pixel data from DOM node.
Returns: Promise<Uint8ClampedArray> - RGBA pixel data
Best for: Image processing, pixel manipulation
const pixelData = await domtoimage.toPixelData(element);interface DomScreenshotOptions {
width?: number; // Override width
height?: number; // Override height
bgcolor?: string; // Background color
quality?: number; // JPEG quality (0-1)
style?: CSSStyleDeclaration; // Additional styles
filter?: (node: Node) => boolean; // Filter nodes
cacheBust?: boolean; // Bust cache with random query
imagePlaceholder?: string; // Placeholder for broken images
}Let users download rendered UI as images:
const png = await domtoimage.toPng(contentElement);
downloadFile(png, 'export.png');Create visual reports from data:
const reports = await Promise.all([
domtoimage.toPng(chart1),
domtoimage.toPng(chart2),
domtoimage.toPng(table),
]);Build screenshot applications:
const screenshots = [];
screenshots.push(await domtoimage.toPng(screen1));
screenshots.push(await domtoimage.toPng(screen2));Auto-capture UI for documentation:
const componentScreenshot = await domtoimage.toSvg(component);The project includes a comprehensive test suite with:
- β 20 infrastructure tests
- β Unit tests for all functions
- β Integration tests
- β Custom test matchers
- β Full TypeScript support
# Run tests once
npm run test:run
# Watch mode
npm run test:watch
# UI dashboard
npm run test:ui
# Coverage report
npm run test:coverageSee TESTING.md for detailed testing information.
Experience the library instantly without any setup:
- dom-screenshot React Demo - Interactive demo with live preview
- Supports SVG, PNG, JPEG capture
- Real-time gallery view
- Auto-download functionality
A complete, production-ready React application demonstrating all features:
Features:
- Capture as SVG, PNG, JPEG
- Live preview gallery
- Auto-download files
- Beautiful responsive UI
- Full TypeScript
Quick Start:
npm run example:devOpens at http://localhost:5173
For detailed information, see:
EXAMPLES_QUICKSTART.md- Quick referenceexamples/README.md- Examples overviewexamples/react-app/README.md- Detailed guide
dom-screenshot/
βββ src/
β βββ dom-screenshot.ts # Main library
β βββ types/
β βββ options.ts # Type definitions
βββ dist/
β βββ dom-screenshot.esm.js # ES Module
β βββ dom-screenshot.min.js # IIFE (minified)
β βββ dom-screenshot.d.ts # TypeScript types
βββ tests/
β βββ setup.ts # Test configuration
β βββ helpers/ # Test utilities
β βββ mocks/ # Mock implementations
β βββ fixtures/ # Test data
β βββ unit/
β βββ simple.test.ts # Infrastructure tests
β βββ basic.test.ts # Feature tests
βββ examples/
β βββ react-app/ # React example application
βββ vitest.config.mts # Test runner config
βββ tsconfig.json # TypeScript config
βββ rollup.config.mjs # Build config
βββ package.json
- Node.js 22.12.0 (pinned with Volta)
- npm or yarn
# Install dependencies
npm install
# Build library
npm run build
# Watch for changes
npm run watchnpm run build # Build production
npm run test:run # Run tests
npm run test:watch # Watch tests
npm run test:ui # Test UI dashboard
npm run example:dev # Run React example
npm run example:build # Build React example- β Full TypeScript migration
- β Strict type checking enabled
- β Modern build tooling (Rollup 4.x, TypeScript 5.x)
- β ESM and CommonJS dual output
- β Complete test suite (20+ tests passing)
- β Production-ready React example
- β Comprehensive documentation
| Metric | Status |
|---|---|
| TypeScript | β Full coverage with strict mode |
| Tests | β 20+ tests passing |
| Build | β 0 errors |
| Output | β ESM + IIFE dual format |
| Types | β Complete definitions |
| Docs | β Comprehensive guides |
- β Chrome/Chromium (latest)
- β Firefox (latest)
- β Safari (latest)
- β Edge (latest)
For older browsers, ensure required polyfills are present.
| Format | Use Case | Size | Speed | Quality |
|---|---|---|---|---|
| SVG | UI/Diagrams | Smallest | Fastest | Vector |
| PNG | General Purpose | Medium | Medium | Lossless |
| JPEG | Photos | Smallest | Slower | Lossy |
| Blob | Server Upload | Any | Any | Any |
const png = await domtoimage.toPng(element, {
width: 1920,
height: 1080,
});const png = await domtoimage.toPng(element, {
bgcolor: '#ffffff',
});const jpeg = await domtoimage.toJpeg(element, {
quality: 0.95, // 0 to 1
});const svg = await domtoimage.toSvg(element, {
filter: (node) => {
// Exclude elements with class 'no-capture'
if (node instanceof HTMLElement) {
return !node.classList.contains('no-capture');
}
return true;
},
});const png = await domtoimage.toPng(element, {
cacheBust: true, // Add random query string to URLs
});- Ensure styles are inline or in
<style>tags - External stylesheets may not be included
- Use computed styles for debugging
- SVG capture works in all environments
- PNG/JPEG may need browser environment
- Always use try-catch blocks
- Use SVG for simple UI elements
- Break large captures into sections
- Cache element references
- Ensure library is built:
npm run build - Check Node.js version:
node --version - Try reinstalling:
rm -rf node_modules && npm install
Quick reference for:
- Running tests
- Test commands
- Test patterns
Current test status:
- Test results
- Coverage information
- Known issues
Comprehensive testing:
- Setup details
- Infrastructure overview
- Test organization
Quick start for examples:
- Installation steps
- Running instructions
- Troubleshooting
Examples overview:
- Available examples
- Features demonstrated
- Technologies used
React example details:
- Project structure
- Component documentation
- Customization guide
Testing infrastructure:
- Test setup
- Helper utilities
- Mock implementations
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new features
- Ensure all tests pass
- Submit a pull request
See TESTING.md for test setup instructions.
- Original library: dom-to-image by tsayen
- Modern tooling and TypeScript migration by Muhammad K. Huda
- π Check the documentation files listed above
- π Found a bug? Open an issue
- π¬ Have questions? Check existing issues or discussions
- π Want to contribute? See Contributing section
Ready to capture?
- π¬ Try the Live Demo instantly
- π Read the Quick Start
- π» Check the React Example
Let's start capturing! πΈ