Fast & Accurate DOM to Image Capture with snapDOM

Fast & Accurate DOM to Image Capture with snapDOM
Fast & Accurate DOM to Image Capture with snapDOM
snapDOM is a JavaScript-driven DOM capture tool that converts any HTML element into a scalable SVG image.

It can be useful when you need to generate image previews of UI components, create visual regression tests, build user feedback tools where users screenshot parts of the page, or dynamically generate images from HTML templates on the client side.

Features:

  • Full DOM Capture: Grabs everything, including nested content and Shadow DOM.
  • Style Preservation: Accurately embeds computed styles, pseudo-elements (::before, ::after), and applied fonts.
  • Multiple Export Formats: Output as SVG Data URL, HTMLImageElement (SVG source), HTMLCanvasElement, PNG, JPG, WebP, or SVG Blob.
  • Blazing Fast: Up to 148× faster than alternatives for large captures.
  • Zero Dependencies: Vanilla JS, relying only on standard browser APIs.
  • Exclusion/Placeholder: Options to skip elements (data-capture="exclude") or replace them with text (data-capture="placeholder").

See It In Action:

How to use it:

1. Install snapDOM and import it into your project.

# Yarn
$ yarn add @zumer/snapdom

# NPM
$ npm install @zumer/snapdom
import { snapdom } from '@zumer/snapdom';
// or for specific methods
import { toPng, toCanvas } from '@zumer/snapdom';

2. You can also directly import the library into your HTML document:

<!-- Global object 'snapdom' -->
<script src="https://unpkg.com/@zumer/snapdom@latest/dist/snapdom.min.js"></script>
<!-- Or as ES Module -->
<script type="module">
import { snapdom } from 'https://unpkg.com/@zumer/snapdom@latest/dist/snapdom.mjs';
window.snapdom = snapdom;
</script>

3. Capture an element as an SVG Data URL.

async function captureElement(selector) {
  const targetElement = document.querySelector(selector);
  if (!targetElement) return;
  try {
    // Default capture is SVG Data URL
    const svgDataUrl = await snapdom(targetElement);
    // You can directly use this in an img src
    const img = new Image();
    img.src = svgDataUrl;
    img.style.border = '1px solid #ccc'; // Add border for visibility
    document.body.appendChild(img);
    console.log('SVG Data URL:', svgDataUrl.substring(0, 100) + '...'); // Log prefix
  } catch (error) {
    console.error('snapDOM capture failed:', error);
  }
}
// Example: Capture an element with id="user-card"
captureElement('#user-card');

4. Available API methods. All methods take the target Element as the first argument and an optional options object as the second. They all return a Promise.

  • snapdom(el, options?): Returns SVG Data URL (string). The default and often most useful for sharp, scalable output.
  • snapdom.toImg(el, options?): Returns an HTMLImageElement with the SVG Data URL as its src. Convenient for immediate display.
  • snapdom.toCanvas(el, options?): Returns an HTMLCanvasElement. Useful if you need to further manipulate the image pixel data.
  • snapdom.toPng(el, options?): Returns an HTMLImageElement with a PNG Data URL src.
  • snapdom.toJpg(el, options?): Returns an HTMLImageElement with a JPG Data URL src. Use quality option here.
  • snapdom.toWebp(el, options?): Returns an HTMLImageElement with a WebP Data URL src. Use quality and backgroundColor options.
  • snapdom.toBlob(el, options?): Returns an SVG Blob. Good for sending to servers or using with URL.createObjectURL.

5. Available options.

  • scale (number, default: 1): Applies a scaling factor to the output image. Useful for higher resolution captures.
  • quality (number, 0-1): Sets compression quality for JPG and WebP exports. Ignored for SVG/PNG.
  • backgroundColor (string): CSS color string for the background when exporting to JPG or WebP (which don’t support transparency).

Best Practices & Performance:

Font Loading: snapDOM automatically waits for document.fonts.ready. Ensure your fonts are loaded before initiating the capture if you rely on custom web fonts. If fonts load after the capture starts, they might not render correctly.

CORS: External images (e.g., <img> tags with src pointing to another domain) must be served with permissive CORS headers (Access-Control-Allow-Origin). The browser’s security rules prevent canvas/SVG tainting otherwise. snapDOM tries to fetch and inline these as Data URLs. If it fails due to CORS, the image might be missing.

Complexity: While fast, capturing extremely large or complex DOM trees (thousands of nodes deep) will naturally take longer. Consider capturing smaller, more targeted elements if performance is critical on massive pages.

SVG vs. Raster: SVG output is generally preferred for fidelity and scalability. Use PNG/JPG/WebP mainly when you need a specific raster format or transparency isn’t desired (JPG). SVG captures can sometimes result in larger file sizes if they contain many embedded raster images.

Compared to Alternatives

Library Speed (ms) SVG Output Shadow DOM Pseudo-Elements
snapDOM 12
html2canvas 650 Partial
dom-to-image 320
modern-screenshot 110

FAQs

Q: Why are images from another domain not showing up?

A: This is almost certainly a CORS issue. The server hosting the external image needs to send Access-Control-Allow-Origin headers that permit your site to fetch the image data. Without it, the browser blocks access, and snapDOM can’t inline the image. Check your browser’s console for CORS errors.

Q: My custom web fonts look wrong in the capture.

A: Make sure the font is fully loaded before you call snapdom. snapDOM waits for document.fonts.ready, but if you trigger the capture during font loading, it might capture before the font is applied. Use CSS font-display: block; initially or explicitly await your font loading promises if needed.

Q: Can it capture content inside an <iframe>?

A: No, snapDOM doesn’t capture iframe content due to browser security restrictions (cross-origin limitations). It captures the <iframe> element itself, but not its internal document.

Q: How does scaling work? Does scale: 2 make it twice as slow?

A: The scale option increases the dimensions of the output SVG/Canvas. It might increase processing time slightly, but usually not dramatically like 2x slower. It’s useful for getting higher-resolution PNG/JPG outputs from the intermediate canvas stage. For SVG, it mainly affects the viewBox and width/height attributes.

Q: What’s the difference between snapdom() and snapdom.toImg()?

snapdom() returns a Promise<string> containing the SVG Data URL. snapdom.toImg() returns a Promise<HTMLImageElement> where the src attribute is set to that SVG Data URL. toImg is just a convenience wrapper if you immediately want an <img> tag.

Q: Is there a size limit to what it can capture?

A: There’s no hardcoded limit, but extremely large and complex DOM structures will consume more memory and CPU during capture. Browser limitations on memory or rendering extremely large SVGs/Canvases could theoretically be hit in extreme edge cases, but for typical web pages and components, it should be fine. The performance benchmarks show it handles very large dimensions well compared to others.

The post Fast & Accurate DOM to Image Capture with snapDOM appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading