dom-to-image vs html2canvas vs puppeteer
Client-Side and Server-Side DOM Rendering to Image in Web Applications
dom-to-imagehtml2canvaspuppeteerSimilar Packages:

Client-Side and Server-Side DOM Rendering to Image in Web Applications

dom-to-image, html2canvas, and puppeteer are libraries used to convert HTML content into image formats, but they operate in fundamentally different environments and with distinct capabilities. dom-to-image and html2canvas run entirely in the browser and rasterize DOM elements using canvas or SVG serialization, while puppeteer is a Node.js library that controls a headless Chromium instance to capture full-page screenshots with high fidelity. These tools serve overlapping use cases—such as generating social media previews, saving dashboards, or creating PDFs—but differ significantly in rendering accuracy, performance, security model, and deployment context.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
dom-to-image010,786-3378 years agoMIT
html2canvas031,8213.38 MB1,047-MIT
puppeteer093,82363 kB2952 days agoApache-2.0

Converting Web Content to Images: dom-to-image vs html2canvas vs puppeteer

When you need to turn part or all of a web page into an image—whether for sharing, archiving, or generating reports—you’ll likely consider one of three approaches: pure client-side DOM rasterization (dom-to-image, html2canvas) or server-driven browser automation (puppeteer). Each has trade-offs in fidelity, environment, and complexity. Let’s compare them in real engineering contexts.

🖼️ Rendering Approach: Simulated vs Real Browser

dom-to-image converts the DOM to an inline SVG, then draws that SVG into a <canvas> to export as PNG/JPEG. This means it only supports features that can be expressed in SVG.

// dom-to-image: Export a div to PNG
import domtoimage from 'dom-to-image';

const node = document.getElementById('chart');
const dataUrl = await domtoimage.toPng(node);
const img = new Image();
img.src = dataUrl;
document.body.appendChild(img);

html2canvas walks the DOM tree and re-implements layout and painting logic in JavaScript to draw directly onto a <canvas>. It approximates how the browser renders, but doesn’t use the actual rendering engine.

// html2canvas: Render a div to canvas
import html2canvas from 'html2canvas';

const node = document.querySelector('.dashboard');
const canvas = await html2canvas(node);
document.body.appendChild(canvas);

puppeteer launches a real Chromium instance, navigates to a URL, and takes a screenshot using the browser’s native rendering pipeline—identical to what a user sees.

// puppeteer: Full-page screenshot on the server
import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com/dashboard');
await page.screenshot({ path: 'dashboard.png' });
await browser.close();

💡 Key insight: Only puppeteer uses the actual browser engine. The other two simulate rendering, which leads to gaps in CSS support.

🎨 CSS and Layout Fidelity

Not all CSS renders equally across these tools.

  • dom-to-image struggles with:

    • box-shadow (often ignored)
    • transform (partially supported)
    • Pseudo-elements (::before, ::after)
    • Web fonts (unless manually embedded as data URLs)
  • html2canvas handles more modern CSS:

    • Basic box-shadow and border-radius
    • flexbox and grid (with limitations)
    • transform and opacity
    • But still fails on ::before/::after, filter, and complex gradients
  • puppeteer supports everything Chromium supports—including Web Components, WebGL canvases (as static images), custom fonts, and even video frames (if paused).

Example: Trying to capture a card with a drop shadow and icon font.

// In your HTML
<div id="card" style="box-shadow: 0 4px 12px rgba(0,0,0,0.2); font-family: 'CustomIconFont'">
  <i class="icon-user"></i> Profile
</div>
  • dom-to-image: Shadow missing, icon may render as a box
  • html2canvas: Shadow appears faint or offset; icon works only if font is preloaded
  • puppeteer: Renders exactly as in-browser

🔒 Security and Resource Access

Client-side tools (dom-to-image, html2canvas) are bound by the browser’s same-origin policy:

  • Cannot load cross-origin images unless they have crossorigin="anonymous" and proper CORS headers
  • Cannot access content inside <iframe>s
  • Fonts must be hosted on the same origin or served with CORS

puppeteer, running on your server, bypasses these restrictions:

  • Can load any public URL
  • Can authenticate via cookies or headers before screenshotting
  • Can inject scripts or styles to modify the page before capture
// puppeteer: Add auth header and hide sensitive UI
await page.setExtraHTTPHeaders({ 'Authorization': 'Bearer xyz' });
await page.addStyleTag({ content: '.secret { display: none !important; }' });

This makes puppeteer essential for capturing authenticated dashboards or internal tools.

⚙️ Performance and Bundle Impact

  • dom-to-image: ~20 KB minified. Fast for simple DOM trees, but slows down with large SVGs.
  • html2canvas: ~80 KB minified. CPU-intensive—it parses every computed style and redraws everything in canvas, which can block the main thread.
  • puppeteer: Not bundled in frontend code. Runs on server; startup time includes launching Chromium (~100–500ms), but rendering is fast and offloads work from the client.

For user-triggered exports in a React app, html2canvas might cause noticeable jank on complex pages. dom-to-image is lighter but less accurate. puppeteer shifts the cost to your backend.

📱 Responsive and Full-Page Capture

  • dom-to-image and html2canvas only capture the dimensions of the target DOM element. To capture a full “page,” you must wrap all content in a single scrollable container and set its height explicitly.

  • puppeteer natively supports full-page screenshots:

await page.setViewport({ width: 1920, height: 1080 });
await page.screenshot({ fullPage: true }); // scrolls and stitches automatically

It also lets you emulate devices, network conditions, and media queries.

🧪 Error Handling and Debugging

  • dom-to-image silently drops unsupported features. No error thrown if a font fails to load.
  • html2canvas logs warnings to console for failed resources but continues rendering.
  • puppeteer throws clear errors (e.g., navigation timeout, selector not found) and allows debugging via page.on('console', ...) or saving intermediate HTML.
// Debug puppeteer rendering
await page.evaluate(() => document.body.innerHTML);
// Or save as HTML for inspection
await page.content();

🔄 When to Combine Approaches

In practice, teams often use a hybrid strategy:

  1. Use html2canvas for quick, client-side previews (e.g., “see how your badge will look”)
  2. Send the final request to a puppeteer microservice for high-quality output

This gives users instant feedback while ensuring archival-quality images.

📊 Summary Table

Capabilitydom-to-imagehtml2canvaspuppeteer
EnvironmentBrowser onlyBrowser onlyNode.js (server)
Rendering EngineSVG + CanvasCustom JS rendererReal Chromium
CSS SupportLimited (SVG subset)ModerateFull
Cross-Origin Resources❌ (CORS required)❌ (CORS required)
Full-Page CaptureManual workaroundManual workaround✅ (fullPage: true)
Bundle SizeSmallMediumN/A (server-side)
Auth / Private Pages
DebuggabilityLowMediumHigh

💡 Final Recommendation

  • For simple, public, client-side exports (e.g., shareable charts): start with dom-to-image.
  • For richer UIs under your control (e.g., internal tool dashboards): try html2canvas but test thoroughly.
  • For production-critical, high-fidelity images (e.g., invoices, reports, social previews): use puppeteer on the backend.

Remember: no client-side solution can match the rendering accuracy of a real browser. If pixel perfection matters, puppeteer (or similar headless browsers like Playwright) is the only reliable choice.

How to Choose: dom-to-image vs html2canvas vs puppeteer

  • dom-to-image:

    Choose dom-to-image if you need a lightweight, client-side solution that supports exporting SVG-based elements (like charts from D3) to PNG or JPEG with decent fidelity. It works well when your DOM uses standard CSS and doesn’t rely heavily on external resources like web fonts or cross-origin images. However, avoid it if you require precise rendering of complex layouts, shadows, or modern CSS features, as it serializes the DOM to SVG and may not fully replicate browser rendering.

  • html2canvas:

    Choose html2canvas if you’re working entirely in the browser and need better support for common CSS properties (like flexbox, transforms, and basic shadows) than dom-to-image offers. It paints the DOM onto a canvas by re-implementing layout logic in JavaScript, which gives more accurate results for many real-world UIs—but it still struggles with iframes, pseudo-elements, and certain CSS features. Use it when server-side rendering isn’t an option and you can control the styling constraints of the target element.

  • puppeteer:

    Choose puppeteer if you need pixel-perfect, production-grade screenshots or PDFs of web pages, especially when dealing with complex layouts, web fonts, embedded media, or authentication flows. Since it uses a real Chromium browser under the hood, it renders exactly as a user would see it. However, it requires a Node.js backend and cannot run in the browser, so it’s only suitable for server-side workflows like report generation, visual regression testing, or automated screenshot services.

README for dom-to-image

DOM to Image

Build Status

What is it

dom-to-image is a library which can turn arbitrary DOM node into a vector (SVG) or raster (PNG or JPEG) image, written in JavaScript. It's based on domvas by Paul Bakaus and has been completely rewritten, with some bugs fixed and some new features (like web font and image support) added.

Installation

NPM

npm install dom-to-image

Then load

/* in ES 6 */
import domtoimage from 'dom-to-image';
/* in ES 5 */
var domtoimage = require('dom-to-image');

Bower

bower install dom-to-image

Include either src/dom-to-image.js or dist/dom-to-image.min.js in your page and it will make the domtoimage variable available in the global scope.

<script src="path/to/dom-to-image.min.js" />
<script>
  domtoimage.toPng(node)
  //...
</script>

Usage

All the top level functions accept DOM node and rendering options, and return promises, which are fulfilled with corresponding data URLs.
Get a PNG image base64-encoded data URL and display right away:

var node = document.getElementById('my-node');

domtoimage.toPng(node)
    .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
    })
    .catch(function (error) {
        console.error('oops, something went wrong!', error);
    });

Get a PNG image blob and download it (using FileSaver, for example):

domtoimage.toBlob(document.getElementById('my-node'))
    .then(function (blob) {
        window.saveAs(blob, 'my-node.png');
    });

Save and download a compressed JPEG image:

domtoimage.toJpeg(document.getElementById('my-node'), { quality: 0.95 })
    .then(function (dataUrl) {
        var link = document.createElement('a');
        link.download = 'my-image-name.jpeg';
        link.href = dataUrl;
        link.click();
    });

Get an SVG data URL, but filter out all the <i> elements:

function filter (node) {
    return (node.tagName !== 'i');
}

domtoimage.toSvg(document.getElementById('my-node'), {filter: filter})
    .then(function (dataUrl) {
        /* do something */
    });

Get the raw pixel data as a Uint8Array with every 4 array elements representing the RGBA data of a pixel:

var node = document.getElementById('my-node');

domtoimage.toPixelData(node)
    .then(function (pixels) {
        for (var y = 0; y < node.scrollHeight; ++y) {
          for (var x = 0; x < node.scrollWidth; ++x) {
            pixelAtXYOffset = (4 * y * node.scrollHeight) + (4 * x);
            /* pixelAtXY is a Uint8Array[4] containing RGBA values of the pixel at (x, y) in the range 0..255 */
            pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4);
          }
        }
    });

All the functions under impl are not public API and are exposed only for unit testing.


Rendering options

filter

A function taking DOM node as argument. Should return true if passed node should be included in the output (excluding node means excluding it's children as well). Not called on the root node.

bgcolor

A string value for the background color, any valid CSS color value.

height, width

Height and width in pixels to be applied to node before rendering.

style

An object whose properties to be copied to node's style before rendering. You might want to check this reference for JavaScript names of CSS properties.

quality

A number between 0 and 1 indicating image quality (e.g. 0.92 => 92%) of the JPEG image. Defaults to 1.0 (100%)

cacheBust

Set to true to append the current time as a query string to URL requests to enable cache busting. Defaults to false

imagePlaceholder

A data URL for a placeholder image that will be used when fetching an image fails. Defaults to undefined and will throw an error on failed images

Browsers

It's tested on latest Chrome and Firefox (49 and 45 respectively at the time of writing), with Chrome performing significantly better on big DOM trees, possibly due to it's more performant SVG support, and the fact that it supports CSSStyleDeclaration.cssText property.

Internet Explorer is not (and will not be) supported, as it does not support SVG <foreignObject> tag

Safari is not supported, as it uses a stricter security model on <foreignObject> tag. Suggested workaround is to use toSvg and render on the server.`

Dependencies

Source

Only standard lib is currently used, but make sure your browser supports:

Tests

Most importantly, tests depend on:

  • js-imagediff, to compare rendered and control images

  • ocrad.js, for the parts when you can't compare images (due to the browser rendering differences) and just have to test whether the text is rendered

How it works

There might some day exist (or maybe already exists?) a simple and standard way of exporting parts of the HTML to image (and then this script can only serve as an evidence of all the hoops I had to jump through in order to get such obvious thing done) but I haven't found one so far.

This library uses a feature of SVG that allows having arbitrary HTML content inside of the <foreignObject> tag. So, in order to render that DOM node for you, following steps are taken:

  1. Clone the original DOM node recursively

  2. Compute the style for the node and each sub-node and copy it to corresponding clone

    • and don't forget to recreate pseudo-elements, as they are not cloned in any way, of course
  3. Embed web fonts

    • find all the @font-face declarations that might represent web fonts

    • parse file URLs, download corresponding files

    • base64-encode and inline content as data: URLs

    • concatenate all the processed CSS rules and put them into one <style> element, then attach it to the clone

  4. Embed images

    • embed image URLs in <img> elements

    • inline images used in background CSS property, in a fashion similar to fonts

  5. Serialize the cloned node to XML

  6. Wrap XML into the <foreignObject> tag, then into the SVG, then make it a data URL

  7. Optionally, to get PNG content or raw pixel data as a Uint8Array, create an Image element with the SVG as a source, and render it on an off-screen canvas, that you have also created, then read the content from the canvas

  8. Done!

Things to watch out for

  • if the DOM node you want to render includes a <canvas> element with something drawn on it, it should be handled fine, unless the canvas is tainted - in this case rendering will rather not succeed.

  • at the time of writing, Firefox has a problem with some external stylesheets (see issue #13). In such case, the error will be caught and logged.

Authors

Anatolii Saienko, Paul Bakaus (original idea)

License

MIT