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

The practical browser workflow is: select the HTML element, render it to a canvas with html2canvas, then export that canvas as a PNG with toBlob(). This works well for cards, invoices, charts and previews, but it reconstructs the DOM rather than taking native browser pixels. If you need a faithful page screenshot, use Playwright, Puppeteer or a screenshot API instead.

Convert an HTML element to PNG in the browser

Install html2canvas in your application:

npm install html2canvas

Give the element you want to export a stable selector:

<article id="capture">
  <h1>Monthly report</h1>
  <p>Revenue increased 18%.</p>
</article>
<button id="download">Download PNG</button>

Then capture it and download the result:

import html2canvas from 'html2canvas';

document.querySelector('#download').addEventListener('click', downloadPng);

async function downloadPng() {
  const element = document.querySelector('#capture');
  if (!element) throw new Error('Capture element not found');

  const canvas = await html2canvas(element, {
    backgroundColor: null,
    scale: window.devicePixelRatio,
    useCORS: true
  });

  const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
  if (!blob) throw new Error('PNG export failed');

  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'capture.png';
  link.click();
  URL.revokeObjectURL(url);
}

html2canvas(element) returns a Promise that resolves to a canvas. backgroundColor: null preserves transparency where the element has no background, scale controls output density (and defaults to the device pixel ratio), and useCORS: true asks the browser to load images with CORS enabled. CORS still depends on the image server returning the required headers.

Use a data URL when you need inline image data

For a small image or an <img src="data:..."> value, call:

const dataUrl = canvas.toDataURL('image/png');

PNG is the required canvas export format and is also the fallback when no format is supplied or an unsupported format is requested. A data URL contains the complete encoded image in a JavaScript string, so it can consume substantial memory for a large capture. Prefer toBlob() and an object URL for downloads and larger images.

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.

Make the capture reliable

Wait for images and fonts

Start the capture only after the content is ready. An image that is still loading, a web font that has not resolved, or data inserted by a framework after the click can produce missing or incorrectly sized content.

async function waitForImages(root) {
  const images = [...root.querySelectorAll('img')];
  await Promise.all(images.map(img => {
    if (img.complete) return img.decode?.().catch(() => {});
    return new Promise(resolve => {
      img.addEventListener('load', resolve, { once: true });
      img.addEventListener('error', resolve, { once: true });
    });
  }));
}

async function captureReadyElement() {
  const element = document.querySelector('#capture');
  if (!element) throw new Error('Capture element not found');
  await document.fonts?.ready;
  await waitForImages(element);
  return html2canvas(element, { useCORS: true });
}

If your application updates the element asynchronously, wait for that state explicitly rather than relying on a fixed timeout. A timeout can be useful for animations, but it is less dependable than waiting for the actual resource or selector.

Choose the output scale

The CSS size of a 600×400 element is not necessarily its PNG pixel size. With scale: window.devicePixelRatio, a two-times display produces roughly 1,200×800 output. Higher scale improves sharpness but increases canvas dimensions, memory use and encoding time. For predictable files, set an explicit scale and test on the target devices.

const canvas = await html2canvas(element, {
  scale: 2,
  width: element.scrollWidth,
  height: element.scrollHeight
});

Use the element’s scroll dimensions when its contents extend beyond its visible box. Extremely large canvases can become blank or partially rendered because maximum dimensions vary by browser, GPU, operating system and device; there is no universal safe limit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Preserve transparency or force a background

Use backgroundColor: null when transparent areas should remain transparent. For a solid PNG background, specify a CSS color:

const canvas = await html2canvas(element, {
  backgroundColor: '#ffffff'
});

Remember that a transparent page background and a transparent element background are different. Inspect the computed styles of the element and its ancestors when the result appears unexpectedly white.

Understand html2canvas fidelity

html2canvas walks the DOM and computed styles, then draws what it understands onto a canvas. It is not a native screenshot of the browser compositor. The project’s documentation states that the result “may not be 100% accurate to the real representation of the page.” Unsupported or partially supported CSS, pseudo-elements, filters, complex transforms, web fonts, SVG behavior and dynamic content can therefore differ from what you see on screen.

  • Validate important captures in every target browser.
  • Test real fonts, SVGs, gradients, transforms and pseudo-elements instead of assuming they will match.
  • Hide transient controls or animation states before capture.
  • For an extension tab or a complete page that must match browser pixels, use a native browser screenshot API.

Do not describe html2canvas output as pixel-perfect unless you have validated the specific page and browser combination.

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.
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.

Fix cross-origin images and tainted canvases

Canvas export is subject to the browser’s same-origin security rules. An image from another origin can be omitted, or it can make the canvas origin-unclean. In the latter case, toBlob() or toDataURL() can fail with a security error.

  1. Keep assets on the same origin when possible.
  2. For a remote asset, use crossorigin="anonymous" and useCORS: true.
  3. Configure the asset server to return an appropriate Access-Control-Allow-Origin header.
  4. If you control neither server, use a carefully controlled same-origin proxy that fetches and serves the asset with your policy.
<img src="https://cdn.example.com/chart.png" crossorigin="anonymous" alt="Chart">

allowTaint is not a security bypass. An origin-tainted canvas is still unreadable for export, so enabling it does not solve the problem.

When to use a real browser screenshot instead

Use Playwright or Puppeteer when the requirement is the actual rendered page rather than a DOM reconstruction, especially for server-side jobs, authenticated pages, full-page captures and CSS features html2canvas does not reproduce. A typical automation flow launches a browser, navigates to the URL, waits for the page state and calls the browser’s screenshot method. This requires a Node.js process and browser binaries, unlike the client-only html2canvas approach.

Requirement Best fit Reason
Export one visible component in a web app html2canvas Runs in the user’s browser and needs no server browser.
Exact browser pixels Playwright or Puppeteer Captures the browser compositor rather than rebuilding CSS.
Server-side or scheduled capture Playwright, Puppeteer or an API Provides a controlled browser or hosted rendering service.
Content already drawn in a canvas That canvas’s export methods No DOM reconstruction is necessary.

There is no universal speed or accuracy winner among libraries. Capture a representative page in the browsers, fonts and viewport sizes your product supports, then choose based on fidelity, security boundaries, operational complexity and cost.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

Export an existing canvas directly

If your chart or game is already a canvas, skip html2canvas:

const source = document.querySelector('#chart');
const blob = await new Promise(resolve => source.toBlob(resolve, 'image/png'));
if (!blob) throw new Error('Canvas export failed');

const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'chart.png';
link.click();
URL.revokeObjectURL(url);

The same origin-clean rule applies. If foreign content was drawn into the canvas without suitable CORS permission, reading or exporting it can raise a SecurityError.

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 provides a hosted screenshot API when you need a URL rendered by a real browser rather than reconstructed in the client. It accepts 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 response headers identify the page verdict and billing result.

One GET request returns PNG, JPEG, WebP or PDF:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for all parameters. The same endpoint supports full-page lazy-image loading, CSS-selector element capture, dark mode, 12 device presets or custom viewports, retina scale, PDF paper and page settings, custom CSS and JavaScript, pre-capture clicks, hidden selectors, selector or network-idle waits, request and resource blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, usage data and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify migration.

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

There is also an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots, with every feature available on every plan. Create a free ScreenshotNeo account to start.

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.

Troubleshooting checklist

The element is missing or the script throws “Capture element not found”

  • Run the code after the element exists, or wait for your framework’s mounted/rendered state.
  • Check the selector and confirm the element is not inside a closed shadow root.

Images are blank

  • Wait for image completion and decoding.
  • Check the image response’s CORS headers and use crossorigin="anonymous".
  • Use a same-origin proxy when you control the asset pipeline.

The PNG differs from the page

  • Check unsupported CSS, pseudo-elements, fonts, SVGs, transforms and animation timing.
  • Use a real browser screenshot for pixel fidelity.

The result is cropped

  • Capture the correct element and account for scrollWidth and scrollHeight.
  • Check overflow rules and test a smaller scale.

The output is blank or the tab runs out of memory

  • Reduce scale or split a very large capture into sections.
  • Test platform-specific canvas limits; do not rely on a single maximum dimension.

The download does not start

  • Trigger it from a user gesture where browser popup rules require one.
  • Use toBlob() and an object URL.
  • If immediate revocation fails in a target browser, defer URL.revokeObjectURL(url) until the download action has started.

Performance and cost decisions

  • Client capture: avoids a server browser, but uses the user’s CPU and memory and is constrained by that browser’s CORS policy.
  • Native automation: produces closer browser pixels, but requires browser processes, startup time, isolation and maintenance.
  • Hosted API: moves rendering and cleanup off your infrastructure. Check output verdicts, cache behavior, viewport, wait conditions and image dimensions in your integration.
  • Encoding: use PNG for lossless UI text and transparency. Use JPEG or WebP when the receiving system accepts them and smaller files matter.

Measure representative pages rather than assuming a fixed capture time. Fonts, third-party resources, network-idle waits, full-page lazy loading and large output dimensions all affect latency and memory.

FAQ

Can JavaScript convert a whole webpage to PNG without a library?

Not reliably from ordinary page JavaScript. The DOM does not expose a general native “render this element to PNG” method; use a DOM renderer such as html2canvas or a real-browser screenshot API.

Why is PNG larger than expected?

PNG is lossless, and device-pixel-ratio or high scale settings multiply the pixel count. Lower the scale, resize the result, or choose WebP when transparency and lossless output are not required.

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

Can I run html2canvas in Node.js?

It depends on window, document and browser computed styles, so it is not a Node.js server renderer. Use Playwright, Puppeteer or a hosted screenshot service for Node-side work.

Should I use toDataURL() or toBlob()?

Use toBlob() for downloads and larger images; use toDataURL() when you specifically need an inline data URL.

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.