Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To capture exactly what a browser rendered, use Playwright and a locator screenshot: await page.locator('#invoice').screenshot({ path: 'invoice.png' }); This clips the image to one element instead of taking a full-page screenshot and cropping it later. If the image must be generated inside your web page for a visitor to download, use html2canvas (or a similar DOM-to-image library), while accepting that it reconstructs the element rather than recording browser pixels.

The right choice depends on where the code runs, how faithfully the result must match the screen, whether cross-origin assets are involved, and whether you need a file, data URL, or byte buffer.

Choose the capture method first

Requirement Best fit Result and trade-off
Automated tests, server jobs, or a developer script Playwright locator screenshot Captures the browser’s rendered output, clipped to the selected element; saves a file or returns a buffer.
A button in your own web app that lets visitors export a card or report html2canvas Runs in the page and produces a canvas or data URL, but rebuilds the image from DOM and supported CSS.
DOM-to-image output with PNG, JPEG, or WebP data modern-screenshot Its documented domToPng(node) API returns image data; verify current CORS and embedding behavior before production use.

Use Playwright when pixel fidelity matters. Use a DOM-to-image library when the export must happen in the visitor’s browser without a separate automation service. The two approaches are not interchangeable: one records a browser surface, while the other creates a new rendering from page information.

Capture one rendered element with Playwright

Playwright’s locator API is the most direct way to screenshot a known element. The locator waits for the element according to Playwright’s normal actionability rules, then clips the screenshot to that element’s bounding box.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Install and create a minimal script

npm install -D playwright
npx playwright install

Create element-shot.js:

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage({
    viewport: { width: 1440, height: 900 },
    deviceScaleFactor: 1
  });

  await page.goto('https://example.com', { waitUntil: 'networkidle' });
  await page.locator('#capture').screenshot({
    path: 'element.png',
    type: 'png'
  });

  await browser.close();
})();

Replace https://example.com and #capture with your page and selector. A class selector such as .header, an attribute selector such as [data-testid="receipt"], or a role-based locator can be used. Prefer a stable test ID or semantic locator over a class that exists only for styling.

Wait for dynamic content explicitly

A page can be technically loaded while the target is still being populated by JavaScript. Wait for a meaningful condition before taking the shot:

await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
await page.locator('[data-testid="report"]').waitFor({ state: 'visible' });
await page.locator('[data-testid="report"]').screenshot({ path: 'report.png' });

If a chart animates, wait for the application to expose a ready marker, or add a short, deliberate delay after the element is visible. Waiting for a selector is more reliable than guessing that a fixed page-load event means all data is ready.

Choose image type, scale, and bytes

PNG is lossless and suitable for text or UI screenshots. JPEG is smaller for photographic content; WebP can provide a useful size-quality compromise where your consumer supports it. You can keep the result in memory instead of writing a file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const imageBuffer = await page.locator('#capture').screenshot({
  type: 'png'
});
// imageBuffer is a Buffer that can be uploaded, hashed, or attached to a test result.

Set deviceScaleFactor on the browser context when you need a high-density image. A factor of 2 produces more pixels for the same CSS dimensions, but also increases memory and file size. Keep viewport, fonts, locale, timezone, and color scheme fixed when screenshots are compared in visual tests.

Element screenshots versus full-page screenshots

page.screenshot({ fullPage: true }) captures the entire document. It is useful for a page archive, not for a known card or component. A locator screenshot avoids a later crop, preserves the element’s current layout, and excludes unrelated navigation, ads, and whitespace.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Generate a downloadable image with html2canvas

When the export control is part of your site, html2canvas can render a selected node into a canvas and turn that canvas into a PNG download.

<button id="download" type="button">Download card</button>
<div id="capture">Your report card</div>
<script type="module">
  import html2canvas from 'html2canvas';

  document.querySelector('#download').addEventListener('click', async () => {
    const element = document.querySelector('#capture');
    const canvas = await html2canvas(element, {
      scale: window.devicePixelRatio,
      useCORS: true
    });

    const link = document.createElement('a');
    link.download = 'card.png';
    link.href = canvas.toDataURL('image/png');
    link.click();
  });
</script>

The project examples also support selecting a crop region and excluding nodes with data-html2canvas-ignore. Mark controls that should not appear in the export:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<button data-html2canvas-ignore>Edit</button>

What html2canvas actually captures

html2canvas does not take a literal screenshot of browser pixels. It traverses the DOM and recreates a representation from the information available on the page. Unsupported CSS, browser-specific effects, fonts that have not loaded, and content outside the library’s supported set can therefore differ from what a user sees. For pixel-accurate output, use a real browser screenshot such as Playwright.

Cross-origin images, canvases, and frames

Images from another origin

Images used by html2canvas generally need to be same-origin or served with CORS headers that allow the page to read them. The useCORS: true option asks the browser to request eligible images with CORS, but it cannot grant permission that the image server does not provide. A proxy is another documented approach when you control the proxy and its security policy.

Tainted canvases

If unreadable cross-origin pixels are drawn into a canvas, the canvas becomes tainted. Calling toDataURL() or reading pixel data then throws a security error. An existing tainted canvas on the page can also affect an export that includes it. Fix the image server’s CORS policy, remove the resource from the capture, or move the capture to Playwright.

Cross-origin iframes

Browser same-origin rules prevent html2canvas from reading a document inside a cross-origin iframe. Sandboxed frames without allow-same-origin have the same restriction. You can capture the frame separately from a context that is allowed to load it, or use an integration that renders the complete page in a browser rather than attempting to inspect the iframe DOM from the parent page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Modern DOM-to-image alternatives

The modern-screenshot package documents a domToPng(node) function that returns image data. It can be convenient when you need PNG, JPEG, or WebP data without writing your own canvas-download code. Its npm documentation warns that partial embedding can fail because of CORS, so check the current package release and test your page’s fonts, images, SVG, and embedded content before relying on it.

For any DOM-to-image package, test the exact component states you will export: long text, web fonts, gradients, pseudo-elements, SVG, video, lazy images, and right-to-left text can expose differences that a simple demo does not show.

Reliable element-capture workflow

  1. Give the target a stable identity. Add a unique ID, data attribute, or semantic locator rather than depending on a fragile positional selector.
  2. Set the rendering context. Choose viewport size, device scale, color scheme, locale, timezone, and authentication before loading the page.
  3. Load and wait. Use a suitable navigation event, then wait for the target and for application data, fonts, images, or charts that must appear.
  4. Control unwanted content. Hide transient notifications, pause animations, and disable hover states if they would make output inconsistent.
  5. Capture at the required fidelity. Use Playwright for browser pixels; use html2canvas or modern-screenshot when an in-page export is the requirement.
  6. Validate the output. Check dimensions, transparency, file type, text legibility, and whether all external assets are present.
  7. Handle failures deliberately. Save a diagnostic full-page shot or HTML/log output for automation failures, but do not substitute it for the requested element image.

Common failures and fixes

The selector matches nothing

Playwright reports a timeout when the selector is wrong, the element is inside a different frame, or the page has not rendered it yet. Inspect the DOM, use a stable test ID, and call frameLocator() for a same-origin frame. A cross-origin frame cannot be inspected through the parent document.

The image is blank or clipped

Wait for visibility and content readiness, and verify that the element has non-zero dimensions. For a scrollable component, decide whether you want the visible box or its complete scroll content; a locator screenshot represents the element’s rendered box, not an automatic redesign of its internal overflow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fonts or images are missing

Wait for web fonts and image requests, confirm that the URL is reachable in the capture context, and check CORS when using a DOM-to-image library. Playwright can load the page as a browser, while html2canvas still needs permission to read cross-origin pixels.

html2canvas throws a security error

Look for cross-origin images or an already tainted canvas. Serve assets with appropriate CORS headers, use a configured proxy, exclude the asset, or switch to Playwright.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The result does not match the screen

This is expected when html2canvas encounters unsupported CSS or inaccessible content. Compare the same page with a Playwright locator screenshot to determine whether the discrepancy is reconstruction-related or caused by the page itself.

The screenshot is unexpectedly large

Reduce the viewport or device scale factor, remove unnecessary whitespace, and select WebP or JPEG where lossless PNG is not required. Higher scale improves detail but increases memory, transfer time, and storage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot API and MCP server. Its element-capture option lets you target one element by CSS selector while the service handles the browser session. It also supports full-page captures with lazy images loaded, device presets and arbitrary viewports, dark mode, retina scale, custom CSS and JavaScript, clicks, waits, blocked resources, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, webhooks, bulk capture, PDF output, and a usage API.

Use the API endpoint shown in the ScreenshotNeo documentation:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

The Free plan includes 1,000 shots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try the capture workflow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cost, performance, and operational choices

Local Playwright

A local browser gives you control over authentication, network interception, browser version, and artifacts. It also means maintaining browser binaries, fonts, sandbox settings, concurrency, timeouts, and cleanup. Reuse a browser process for batches, but create isolated contexts when cookies or viewport settings must not leak between jobs.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

In-page rendering

html2canvas avoids a server browser and can feel immediate for a small card. It consumes the visitor’s CPU and memory and is limited by browser security and supported CSS. Do not assume that a successful canvas export proves that every production asset is readable.

Hosted capture

A service removes browser installation and deployment work and can centralize retries, caching, output formats, and asynchronous jobs. Review URL access, authentication handling, retention, and cache TTL for your data before sending private pages.

FAQ

Can I screenshot a div with plain JavaScript?

Plain browser APIs do not provide a general element-to-PNG screenshot. Use browser automation for rendered pixels or a DOM-to-image library for an in-page reconstruction.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I crop a full-page screenshot?

Only when you genuinely need the full page as context. If the target is known, capture the locator directly to avoid crop-coordinate errors and unrelated content.

Which format is best for text-heavy UI?

PNG is the safest default because it preserves sharp edges and text without lossy compression. Choose JPEG or WebP when file size matters more than lossless detail and your delivery path supports the format.

Frequently Asked Questions

Can I screenshot a div with plain JavaScript?

Plain browser APIs do not provide a general element-to-PNG screenshot. Use browser automation for rendered pixels or a DOM-to-image library for an in-page reconstruction.

Should I crop a full-page screenshot?

Only when you genuinely need the full page as context. If the target is known, capture the locator directly to avoid crop-coordinate errors and unrelated content.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which format is best for text-heavy UI?

PNG is the safest default because it preserves sharp edges and text without lossy compression. Choose JPEG or WebP when file size matters more than lossless detail and your delivery path supports the format.

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.