To render one element as a PNG with dom-to-image, first get the element node, then pass it to domtoimage.toPng(node). The promise resolves to a PNG data URL that you can display, download, or pass to other browser code. This captures a rendered DOM subtree; it is not an operating-system screenshot.
Capture one element as a PNG
Install and import the package in a browser application, select the element, and call toPng. Pass the actual DOM node—not a CSS selector string—to the function.
import domtoimage from 'dom-to-image';
const node = document.getElementById('my-element');
if (!node) {
throw new Error('Element not found');
}
domtoimage.toPng(node)
.then((dataUrl) => {
const image = new Image();
image.src = dataUrl;
document.body.appendChild(image);
})
.catch((error) => {
console.error('Could not render element', error);
});
Replace my-element with the target element’s ID. The null check is ordinary defensive DOM code; it is not a special package requirement. The result is a data URL, so the example creates an image and appends it to the document. In an application, you can instead display it in a chosen container or start a download.
Use a selector when the element has no ID
Resolve a selector yourself and pass the returned node:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
const node = document.querySelector('.invoice-card');
if (!node) {
throw new Error('No element matched .invoice-card');
}
const dataUrl = await domtoimage.toPng(node);
This example uses await, so place it inside an async function or an async event handler. The package’s top-level rendering functions return promises.
Choose an output format
The package documents several output functions. Choose based on what the next step in your application needs; the documentation does not establish a current measured quality or performance ranking among them.
| Method | Result | Useful when |
|---|---|---|
toPng(node) |
PNG data URL | You want a lossless raster image that is easy to display or store as a data URL. |
toJpeg(node, options) |
JPEG data URL | You want a compressed raster image; set quality from 0 to 1. |
toSvg(node) |
SVG data URL | You prefer the serialized SVG container output. |
toBlob(node) |
Blob | Downstream browser code expects a Blob rather than a data URL. |
toCanvas(node) |
Canvas | You need to continue working with a canvas in browser code. |
toPixelData(node) |
Raw pixel data | You need pixel values for image processing. |
All of these functions accept a DOM node and optional rendering options, and return promises. See the project README for the documented API and examples.
Adjust the render with options
Options are passed as the second argument. Use them to set dimensions or background, alter the target’s rendered style, exclude descendant elements, and handle image fetch failures.
Recommended Free Tools
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
filter(node)returnstrueto keep a descendant orfalseto exclude it. The filter is not called on the root capture node; excluding a parent also excludes its descendants.bgcolorsets a background color for the output.widthandheightset the rendered node dimensions.styleapplies style overrides to the node before rendering.qualitysets JPEG image quality from 0 to 1.cacheBustappends the current time to resource URLs.imagePlaceholderprovides a data URL to use when an image fetch fails. Without a placeholder, an image failure throws.
Exclude a control from the captured element
For example, this filter removes descendant buttons such as a print control:
function filter(node) {
return node.tagName !== 'BUTTON';
}
const node = document.getElementById('my-element');
if (!node) throw new Error('Element not found');
const dataUrl = await domtoimage.toPng(node, { filter });
The filter cannot remove the root node itself. If the button is the root capture target, choose a containing element instead or prepare a different capture target.
Set a background or output size
const dataUrl = await domtoimage.toPng(node, {
bgcolor: '#ffffff',
width: 900,
height: 600
});
Use dimensions appropriate to the intended output. Changing the dimensions affects the render; it does not make the result a native screenshot of the browser window.
What dom-to-image does under the hood
The original project describes a rendering pipeline that recursively clones the selected element, copies computed styles, recreates pseudo-elements, embeds web fonts and images, serializes the clone to XML, and wraps it in an SVG foreignObject. For PNG and pixel output, it loads that SVG through an image and draws it to an off-screen canvas. This is why a DOM render can differ from a browser-native capture: resource fetching, SVG foreignObject behavior, canvas security, and browser support all matter. The algorithm is described in the original project documentation.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Prepare the page and handle common failures
Wait until the target’s layout, stylesheets, fonts, and images are ready before calling the renderer. That is practical guidance based on the clone-and-fetch workflow: if the page is still changing or a resource cannot be fetched, the resulting image can be incomplete or the promise can reject.
The target is missing or the output is empty
- Confirm the selector matches an element at the time the capture runs. A framework may render the target asynchronously.
- Run the capture after the target has been inserted and its layout has settled.
- Check that the element has visible dimensions and is not hidden by the page’s styles.
An image or other remote resource fails
The renderer embeds images and fonts as part of its process, so inaccessible resources can affect completeness. Check that the resource loads in the page and that browser security rules permit it to be fetched for rendering. For an image failure, the documented imagePlaceholder option can provide a fallback data URL; without a placeholder, the failure throws. A placeholder is a fallback, not a way to retrieve a protected remote asset.
The output is tainted or canvas rendering fails
The original README warns that cross-origin content can taint a canvas. Remote images and background images are common sources to investigate. The original documentation also notes a Firefox issue involving some external stylesheets. Check the browser console and test with the specific resource and browser that matter to your application; the project documentation does not establish current browser support for all combinations.
A Safari or Internet Explorer result differs
The original README marks Internet Explorer unsupported because it lacks SVG foreignObject and notes stricter Safari security around foreignObject. Those statements are historical documentation, not recent browser-version verification. Do not treat the README’s old Chrome 49 and Firefox 45 test references as a current compatibility guarantee. Test your actual browser targets and content.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
You are rendering on a server, inside an iframe, or from video
The following limitations are documented by the separate dom-to-image-more fork, and should not be assumed to describe every behavior of the original package: it requires a browser DOM rather than server-only rendering; cross-origin iframe content cannot be accessed; video needs a poster or a caller-created image or canvas representation; and browsers limit canvas dimensions. If you use that fork, test these cases specifically rather than treating them as capabilities of the original package.
When dom-to-image is the right method
Use dom-to-image when your application runs in a browser, the element is part of the page’s DOM, and you want a rendered subtree as an image-like output for client-side display or processing. It is not the same as taking a screenshot of an arbitrary page from a backend service: its rendering depends on the live DOM, accessible resources, browser implementation, and canvas behavior.
For a reliable workflow, select the node explicitly, wait for its contents and styles to load, handle the promise rejection, and test the relevant browser and resource types. No current performance benchmark or universally reliable browser matrix is established in the project documentation.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If you need a screenshot of a URL rather than a DOM node already in your own page, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. Its API can capture an element by CSS selector, along with full-page captures and other page-level options. One GET request returns an image or PDF; the following cURL example saves a WebP capture. See the ScreenshotNeo API documentation for request options.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo removes known cookie and consent banners, newsletter popups, and chat widgets before capture, and each of those cleanup steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; responses include X-Page-Verdict and X-Billed headers. Its MCP server gives AI agents tools for taking screenshots, getting page information, and capturing PDFs. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.
Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots per month with no card.
Frequently Asked Questions
Can dom-to-image capture an element selected by CSS selector directly?
No. Resolve the selector to a DOM node first, then pass that node to the rendering function.
Does toPng return a PNG file?
It resolves to a PNG data URL. Convert or download that result as needed by your application.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Can I remove the root element with filter?
No. The filter is not called on the root capture node; it applies to descendants.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

