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.
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.
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
puppeteeruses the actual browser engine. The other two simulate rendering, which leads to gaps in CSS support.
Not all CSS renders equally across these tools.
dom-to-image struggles with:
box-shadow (often ignored)transform (partially supported)::before, ::after)html2canvas handles more modern CSS:
box-shadow and border-radiusflexbox and grid (with limitations)transform and opacity::before/::after, filter, and complex gradientspuppeteer 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 boxhtml2canvas: Shadow appears faint or offset; icon works only if font is preloadedpuppeteer: Renders exactly as in-browserClient-side tools (dom-to-image, html2canvas) are bound by the browser’s same-origin policy:
crossorigin="anonymous" and proper CORS headers<iframe>spuppeteer, running on your server, bypasses these restrictions:
// 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.
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.
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.
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();
In practice, teams often use a hybrid strategy:
html2canvas for quick, client-side previews (e.g., “see how your badge will look”)puppeteer microservice for high-quality outputThis gives users instant feedback while ensuring archival-quality images.
| Capability | dom-to-image | html2canvas | puppeteer |
|---|---|---|---|
| Environment | Browser only | Browser only | Node.js (server) |
| Rendering Engine | SVG + Canvas | Custom JS renderer | Real Chromium |
| CSS Support | Limited (SVG subset) | Moderate | Full |
| Cross-Origin Resources | ❌ (CORS required) | ❌ (CORS required) | ✅ |
| Full-Page Capture | Manual workaround | Manual workaround | ✅ (fullPage: true) |
| Bundle Size | Small | Medium | N/A (server-side) |
| Auth / Private Pages | ❌ | ❌ | ✅ |
| Debuggability | Low | Medium | High |
dom-to-image.html2canvas but test thoroughly.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.
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.
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.
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.
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.
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 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>
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.
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.
A string value for the background color, any valid CSS color value.
Height and width in pixels to be applied to node before rendering.
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.
A number between 0 and 1 indicating image quality (e.g. 0.92 => 92%) of the JPEG image. Defaults to 1.0 (100%)
Set to true to append the current time as a query string to URL requests to enable cache busting. Defaults to false
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
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.`
Only standard lib is currently used, but make sure your browser supports:
<foreignObject> tagMost 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
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:
Clone the original DOM node recursively
Compute the style for the node and each sub-node and copy it to corresponding clone
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
Embed images
embed image URLs in <img> elements
inline images used in background CSS property, in a fashion similar to
fonts
Serialize the cloned node to XML
Wrap XML into the <foreignObject> tag, then into the SVG, then make it a
data URL
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
Done!
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.
Anatolii Saienko, Paul Bakaus (original idea)
MIT