Introduction
dom-to-image is a lightweight JavaScript library that captures any DOM node and renders it as a raster or vector image. It works entirely in the browser without a server-side rendering step, making it useful for screenshots, exports, and sharing features in web applications.
What dom-to-image Does
- Converts any HTML element to PNG, JPEG, or SVG data URLs
- Preserves CSS styles, pseudo-elements, web fonts, and images
- Handles complex layouts including flexbox and grid
- Returns standard data URLs or raw Blob objects for download
- Runs client-side with no external service dependencies
Architecture Overview
The library recursively clones the target DOM node, inlines all computed styles, converts linked resources (images, fonts) to data URIs via XMLHttpRequest, and serializes the result into an SVG foreignObject. For raster formats, it draws that SVG onto a canvas element and extracts the pixel data.
Self-Hosting & Configuration
- Install via npm or include the UMD bundle from a CDN
- No build step required for basic usage
- Adjust output quality for JPEG with the quality option (0 to 1)
- Set explicit width and height to override auto-sizing
- Use the filter option to exclude specific child nodes from the capture
Key Features
- Zero external dependencies and under 4 KB minified
- Captures pseudo-elements and CSS shadows faithfully
- Returns Promises for clean async integration
- Supports both data URL and Blob output formats
- Works in all modern browsers including mobile Safari
Comparison with Similar Tools
- html2canvas — re-renders DOM to canvas instead of using SVG foreignObject, larger bundle
- html-to-image — modern fork of dom-to-image with TypeScript and extra output formats
- Puppeteer screenshot — server-side headless Chrome, higher fidelity but requires Node.js
- rasterizeHTML — similar SVG foreignObject approach, less maintained
- Canvas API (manual) — full control but requires manual layout reproduction
FAQ
Q: Does it capture cross-origin images? A: Cross-origin images must be served with CORS headers or proxied through your server, otherwise the canvas is tainted and export fails.
Q: Can I capture elements that are off-screen? A: Yes, as long as the element is in the DOM. It does not need to be visible in the viewport.
Q: What about CSS animations? A: The library captures the element at the current animation frame. It does not produce animated output.
Q: Is it maintained? A: The original repository is stable but not actively updated. Community forks like html-to-image continue active development with additional features.