html2canvas vs html-to-image vs dom-to-image
Converting HTML to Images in Browser-Based Applications
html2canvashtml-to-imagedom-to-imageSimilar Packages:
Converting HTML to Images in Browser-Based Applications

dom-to-image, html-to-image, and html2canvas are client-side JavaScript libraries that enable rendering of DOM elements as image files (PNG, JPEG, etc.) directly in the browser. These tools are commonly used for generating screenshots, exporting visual reports, creating shareable content, or capturing UI states without server involvement. All three work by traversing the DOM, interpreting styles and layout, and producing a rasterized image output using canvas or SVG-based techniques.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
html2canvas7,701,95631,7673.38 MB1,046-MIT
html-to-image1,636,1967,013315 kB190a year agoMIT
dom-to-image263,36910,777-3368 years agoMIT

Converting HTML to Images: dom-to-image vs html-to-image vs html2canvas

When you need to turn part of a web page into an image — whether for sharing, exporting, or archiving — these three libraries offer client-side solutions. But they differ significantly in architecture, capabilities, and maintenance status. Let’s break down what each does well and where they fall short.

🧱 Core Architecture: How They Turn HTML into Pixels

dom-to-image works by cloning the target element, converting all styles to inline attributes, serializing it to an SVG foreignObject, and then drawing that SVG onto a canvas. This approach is simple but fragile when dealing with modern CSS.

// dom-to-image
import domtoimage from 'dom-to-image';

domtoimage.toPng(document.getElementById('capture'))
  .then(dataUrl => {
    const img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
  });

html-to-image uses the same underlying technique as dom-to-image but improves the style parsing and serialization logic. It’s essentially a drop-in replacement with better CSS handling.

// html-to-image
import { toPng } from 'html-to-image';

toPng(document.getElementById('capture'))
  .then(dataUrl => {
    const img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
  });

html2canvas takes a completely different approach: it walks the DOM tree, computes the rendered styles using getComputedStyle(), and manually redraws every element onto a canvas using the Canvas 2D API. This gives it far greater control over rendering accuracy.

// html2canvas
import html2canvas from 'html2canvas';

html2canvas(document.getElementById('capture')).then(canvas => {
  document.body.appendChild(canvas);
});

🎨 CSS Support: Flexbox, Grid, and Beyond

If your UI uses modern layout techniques, this is where the libraries diverge sharply.

dom-to-image struggles with:

  • Flexbox and CSS Grid (often renders as block layout)
  • Transforms (especially 3D)
  • Pseudo-elements (::before, ::after)
  • Web fonts (unless manually embedded)

It doesn’t attempt to interpret computed styles deeply — it just copies declared styles, which breaks when layout depends on parent-child relationships.

html-to-image improves support for:

  • Basic flexbox layouts
  • Some grid configurations
  • Better handling of transform and opacity
  • Font loading via fontEmbedCSS option

However, it still relies on SVG serialization, so complex interactions (like z-index stacking contexts) can fail.

// html-to-image with custom font embedding
import { toPng } from 'html-to-image';

toPng(node, {
  fontEmbedCSS: '@import url("https://fonts.googleapis.com/css2?family=Roboto");'
});

html2canvas excels at:

  • Full flexbox and grid support (since it reads computed styles)
  • Accurate z-index and stacking contexts
  • Pseudo-elements (via ignoreElements configuration)
  • Web fonts (with useCORS: true and proper font hosting)
  • Box shadows, borders, and background gradients
// html2canvas with CORS and logging
html2canvas(node, {
  useCORS: true,
  logging: false,
  allowTaint: false
});

⚠️ Note: html2canvas cannot render iframes, plugins, or video elements — none of these libraries can, due to browser security restrictions.

🖼️ Output Quality and Performance

dom-to-image produces decent quality for simple layouts but often fails silently on complex ones. It’s fast because it offloads rendering to the browser’s SVG engine, but that also means less control.

html-to-image offers similar performance to dom-to-image but with fewer visual glitches thanks to better preprocessing. Still limited by SVG’s inability to perfectly mimic HTML rendering.

html2canvas is slower — especially on large DOM trees — because it manually draws every pixel. But you get pixel-perfect output that matches what the user sees, including subtle effects like text antialiasing and blend modes.

For high-DPI (retina) displays, html2canvas supports scaling:

// html2canvas with scale for high DPI
html2canvas(node, {
  scale: window.devicePixelRatio
});

Neither dom-to-image nor html-to-image handle device pixel ratio automatically — you’d need to scale the canvas yourself post-render.

🔒 Cross-Origin and Security Considerations

All three libraries face the same fundamental limitation: they cannot render images or fonts from external domains unless those resources are served with CORS headers.

html2canvas provides explicit options to handle this:

  • useCORS: true — attempts to load cross-origin images if the server allows it
  • allowTaint: false (default) — prevents tainted canvases that would block toDataURL()
// Safe html2canvas config for mixed content
html2canvas(node, {
  useCORS: true,
  allowTaint: false
});

dom-to-image and html-to-image embed images as base64 data URLs during serialization. If an image is cross-origin and lacks CORS headers, it will either be omitted or cause the entire render to fail — with little feedback.

🛠️ Maintenance and Reliability

dom-to-image is effectively deprecated. Its GitHub repository shows no meaningful updates since 2018, and the npm page includes community warnings about its limitations. Do not use it in new projects.

html-to-image is actively maintained as of 2024, with regular bug fixes and improvements to CSS compatibility. It’s the spiritual successor to dom-to-image.

html2canvas remains under active development, with frequent releases addressing edge cases in modern browsers. It has the largest test suite and best documentation of the three.

📦 Bundle Size and Dependencies

  • dom-to-image: ~15 KB minified (no dependencies)
  • html-to-image: ~20 KB minified (no dependencies)
  • html2canvas: ~90 KB minified (larger due to comprehensive rendering logic)

If you’re building a lightweight utility (e.g., a browser extension), html-to-image offers the best balance. For mission-critical applications where visual fidelity matters (e.g., financial dashboards, design tools), html2canvas is worth the extra weight.

🔄 Migration Path

If you’re currently using dom-to-image, migrating to html-to-image is nearly seamless:

// Before (dom-to-image)
import domtoimage from 'dom-to-image';
domtoimage.toPng(node);

// After (html-to-image)
import { toPng } from 'html-to-image';
toPng(node);

Switching to html2canvas requires more refactoring since it returns a HTMLCanvasElement instead of a data URL, but gives you more control:

// Convert html2canvas output to data URL if needed
html2canvas(node).then(canvas => {
  const dataUrl = canvas.toDataURL('image/png');
});

✅ When to Use Which

ScenarioRecommended Library
Simple static content (text, basic boxes)html-to-image
Modern layouts (flexbox, grid, transforms)html2canvas
High-fidelity rendering (reports, dashboards)html2canvas
Lightweight bundle requirementhtml-to-image
Legacy project already using dom-to-imageKeep it (but plan migration)
New project with complex UIhtml2canvas

💡 Final Advice

Start with html-to-image if your use case is straightforward — it’s small, fast, and good enough for most marketing pages, forms, or simple cards. Switch to html2canvas when you notice missing styles, layout shifts, or font issues. And avoid dom-to-image entirely unless you’re maintaining old code that hasn’t broken yet.

Remember: no client-side library can perfectly replicate browser rendering. Always test with real-world content, especially if your app uses dynamic theming, custom fonts, or responsive layouts.

How to Choose: html2canvas vs html-to-image vs dom-to-image
  • html2canvas:

    Choose html2canvas if you require the most comprehensive rendering fidelity, including support for complex CSS properties, web fonts, pseudo-elements, and cross-origin images (with proper CORS setup). It uses a more sophisticated rendering engine that mimics browser painting behavior more closely, though at the cost of larger bundle size and potentially slower performance on large DOM trees.

  • html-to-image:

    Choose html-to-image if you want a modern, actively maintained fork of dom-to-image with improved support for contemporary CSS layouts (including flexbox and grid), better font handling, and ongoing bug fixes. It retains the same core API but addresses many of the original package’s shortcomings, making it a solid choice for most new browser-based image capture needs.

  • dom-to-image:

    Choose dom-to-image if you're working on a legacy project that already uses it or if you need a lightweight solution with minimal dependencies. However, note that this package is no longer actively maintained and has known limitations with modern CSS features like flexbox, grid, and certain transforms. Avoid it for new projects unless you have specific compatibility requirements.

README for html2canvas

html2canvas

Homepage | Downloads | Questions

Gitter CI NPM Downloads NPM Version

JavaScript HTML renderer

The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

How does it work?

The script renders the current page as a canvas image, by reading the DOM and the different styles applied to the elements.

It does not require any rendering from the server, as the whole image is created on the client's browser. However, as it is heavily dependent on the browser, this library is not suitable to be used in nodejs. It doesn't magically circumvent any browser content policy restrictions either, so rendering cross-origin content will require a proxy to get the content to the same origin.

The script is still in a very experimental state, so I don't recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made.

Browser compatibility

The library should work fine on the following browsers (with Promise polyfill):

  • Firefox 3.5+
  • Google Chrome
  • Opera 12+
  • IE9+
  • Safari 6+

As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported.

Usage

The html2canvas library utilizes Promises and expects them to be available in the global context. If you wish to support older browsers that do not natively support Promises, please include a polyfill such as es6-promise before including html2canvas.

To render an element with html2canvas, simply call: html2canvas(element[, options]);

The function returns a Promise containing the <canvas> element. Simply add a promise fulfillment handler to the promise using then:

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

Building

You can download ready builds here.

Clone git repository:

$ git clone git://github.com/niklasvh/html2canvas.git

Install dependencies:

$ npm install

Build browser bundle

$ npm run build

Examples

For more information and examples, please visit the homepage or try the test console.

Contributing

If you wish to contribute to the project, please send the pull requests to the develop branch. Before submitting any changes, try and test that the changes work with all the support browsers. If some CSS property isn't supported or is incomplete, please create appropriate tests for it as well before submitting any code changes.