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

Install html2canvas, select the element you want, and await the Promise it returns. The Promise resolves to a <canvas> that you can download as PNG, JPEG, or another browser-supported format. This is a browser-side DOM reconstruction—not a pixel-perfect monitor capture—so CSS support, cross-origin images, and very large pages require planning.

What html2canvas actually captures

The html2canvas project describes its script as allowing you to take “screenshots” of webpages or parts of them directly in the user’s browser. It walks the DOM, reads supported styles, and redraws the result on a canvas. It does not ask the operating system for a bitmap of the browser window. Unsupported CSS, browser rendering differences, plugins, cross-origin restrictions, and dynamic content can therefore make the canvas differ from what a user sees.

The library is intended for client-side browser code. For server-side generation, the project FAQ recommends driving a headless browser with Puppeteer or Playwright instead. For browser extensions, the FAQ recommends the browser’s native extension screenshot API rather than html2canvas.

Install and capture an element

Install with npm, Yarn, or pnpm

npm install html2canvas

# or
yarn add html2canvas

# or
pnpm add html2canvas

Import the package in your application, then call it after the target element has rendered. The selector must resolve to an element; wait for fonts, images, and application data if they arrive asynchronously.

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.
import html2canvas from 'html2canvas';

const element = document.querySelector('#capture');
if (!element) throw new Error('Missing #capture element');

const canvas = await html2canvas(element);

const link = document.createElement('a');
link.download = 'screenshot.png';
link.href = canvas.toDataURL('image/png');
link.click();

The same API works when the library is loaded from a built browser release: pass an element and an options object, and handle the returned Promise.

A complete button example

<button id="save-shot" type="button">Save card</button>
<article id="capture">
  <h1>Release summary</h1>
  <p>This entire article will be rendered to an image.</p>
</article>

<script type="module">
  import html2canvas from 'html2canvas';

  document.querySelector('#save-shot').addEventListener('click', async () => {
    const target = document.querySelector('#capture');
    const canvas = await html2canvas(target);
    const link = document.createElement('a');
    link.download = 'release-summary.png';
    link.href = canvas.toDataURL('image/png');
    link.click();
  });
</script>

Choose output format, density, and background

PNG is lossless and is the format used by the project’s download example. JPEG is smaller for photographic content but does not preserve transparency. WebP support depends on the browser. Pass the MIME type and optional quality to toDataURL:

const png = canvas.toDataURL('image/png');
const jpeg = canvas.toDataURL('image/jpeg', 0.85);
const webp = canvas.toDataURL('image/webp', 0.85);

By default, scale follows window.devicePixelRatio. A high-density display can therefore produce a large canvas. Lower it to reduce memory and output size, or raise it for sharper text when the target remains within canvas limits.

const canvas = await html2canvas(target, {
  scale: 1,                 // predictable, smaller output
  backgroundColor: '#ffffff'
});

const transparent = await html2canvas(target, {
  backgroundColor: null
});

Capture a crop or a specific region

Use x, y, width, and height to define the rendered crop. Coordinates are relative to the element being rendered. This is useful when a card contains controls that should not appear in the exported image.

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 #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.
const canvas = await html2canvas(document.querySelector('#capture'), {
  x: 20,
  y: 10,
  width: 640,
  height: 360,
  scale: 2
});

For an element that is partly outside the viewport, set the viewport dimensions used during rendering. Media queries are evaluated against these values.

const target = document.querySelector('#capture');
const canvas = await html2canvas(target, {
  windowWidth: target.scrollWidth,
  windowHeight: target.scrollHeight
});

scrollX and scrollY let you control scroll offsets, including the position of fixed elements. Test fixed headers and sticky controls because their appearance depends on the simulated scroll position.

Exclude buttons, menus, and other UI

Add data-html2canvas-ignore to markup that should never be rendered:

<button data-html2canvas-ignore>Delete</button>

For conditional rules, provide ignoreElements. The predicate receives each element while html2canvas traverses the cloned document.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const canvas = await html2canvas(document.querySelector('#capture'), {
  ignoreElements: element =>
    element.matches('.print-only-off, [aria-hidden="true"]')
});

Make cross-origin images work

Images hosted on another origin are constrained by browser security. With the default allowTaint: false, resources that would taint the canvas may be skipped. Setting useCORS: true only requests the image with CORS; the image server must return an appropriate Access-Control-Allow-Origin header. It is not a way to bypass 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.
const canvas = await html2canvas(document.querySelector('#capture'), {
  useCORS: true
});

If you control the application, configure the image host to allow the requesting origin and ensure the image URL is cacheable without redirecting to a host that omits CORS headers. If you cannot change the remote server, the documented alternative is a proxy URL:

const canvas = await html2canvas(target, {
  proxy: 'https://your.example/proxy'
});

The proxy must fetch the asset and return it in a way the browser can use. A canvas containing disallowed cross-origin pixels cannot be safely read or exported with toDataURL.

Full-page and long-element captures

There is no unlimited canvas. Browser and platform limits vary, and an oversized canvas can be blank or partially rendered without a useful exception. The project FAQ gives approximate examples observed in current browsers: Chrome/Chromium and Firefox around 32,767 pixels for a maximum dimension, with approximate area limits of 268 megapixels and 472 megapixels respectively; desktop Safari is also around 32,767 pixels. iOS Safari is lower and depends on device memory. Treat these as rough, variable examples, not guarantees.

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

For a document or component that is clipped, render using its scroll dimensions:

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
const target = document.querySelector('#long-report');
const canvas = await html2canvas(target, {
  windowWidth: target.scrollWidth,
  windowHeight: target.scrollHeight,
  width: target.scrollWidth,
  height: target.scrollHeight
});

Reduce scale, split a long report into sections, or capture pages separately when memory usage is high. Test on every browser and device class you support. A blank result can be a size-limit failure rather than a selector bug.

Adjust the cloned document before rendering

The onclone callback receives the cloned document used for the capture. You can temporarily remove animations, reveal content, or change styles without altering the live page.

const canvas = await html2canvas(target, {
  onclone: clonedDocument => {
    clonedDocument.querySelectorAll('.loading, .live-cursor')
      .forEach(node => node.remove());
    clonedDocument.querySelectorAll('*').forEach(node => {
      node.style.animation = 'none';
      node.style.transition = 'none';
    });
  }
});

Use this for deterministic output, but keep the callback fast. It modifies only the clone, so application state remains unchanged.

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

Common failures and precise fixes

Symptom Likely cause Fix
Images are missing Remote image lacks CORS permission, image is not loaded yet, or URL redirects Wait for images, set useCORS: true, configure the image host’s CORS headers, or use a correctly configured proxy.
toDataURL throws a security error The canvas is tainted by cross-origin pixels Serve assets with CORS permission or proxy them; browser policy cannot be bypassed.
Output is blank or cuts off Canvas exceeds browser or device limits, or dimensions describe only the viewport Use scroll dimensions, lower scale, split the capture, and test the target browser.
CSS differs from the page The renderer supports only part of CSS and reconstructs the DOM Prefer supported layout and paint properties, use onclone to simplify styles, or use a browser screenshot API when pixel fidelity matters.
Fonts or late data are absent Capture starts before resources finish loading Trigger capture after your data/rendering state is ready and await font and image readiness.
Nothing happens in Node.js html2canvas relies on browser APIs Run it in the browser, or use Puppeteer/Playwright for server-side screenshots.

When html2canvas is the wrong tool

Need Better fit Reason
In-page export of a card or report html2canvas No server browser is required; capture runs in the user’s browser.
Browser extension screenshot Native extension screenshot API The html2canvas FAQ specifically recommends the browser API and avoids canvas limits.
Server-side, repeatable capture Puppeteer or Playwright They drive a headless browser and capture the browser-rendered page.
Pixel-accurate viewport image Browser screenshot API or headless browser Those capture browser output rather than reconstructing supported DOM and CSS.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For automated website screenshots, ScreenshotNeo provides a GET API and an MCP server for AI agents. It removes cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, with the result identified by X-Page-Verdict and X-Billed headers. Claude, Cursor, and other MCP clients can use take_screenshot, get_page_info, and capture_pdf.

See the ScreenshotNeo API documentation for all options, including full-page lazy-image loading, CSS-selector element capture, device presets, retina scale, PDF settings, custom CSS and JavaScript, click and wait actions, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, TTL caching, signed links, webhooks, bulk capture, usage, and OpenAPI compatibility.

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.
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}`);

The Free plan includes 1,000 shots per 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.

Performance and reliability checklist

  • Capture only the element or crop you need.
  • Use a deliberate scale; higher density consumes more memory.
  • Wait for application data, fonts, and images before calling html2canvas.
  • Disable animations in onclone for repeatable output.
  • Set viewport and scroll dimensions for off-screen content.
  • Use CORS headers or a proxy for remote images.
  • Split very long documents and test low-memory mobile devices.
  • Catch rejected Promises and report a useful retry path to users.

FAQ

Can html2canvas capture an iframe?

Only content the page is permitted to read can be reconstructed. A cross-origin iframe remains protected by the browser’s origin rules; capture the framed application itself or use a browser-level screenshot method.

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

Does html2canvas capture a video frame?

Video and other complex browser-managed content may not reproduce reliably because the library redraws supported DOM and CSS rather than taking a compositor screenshot. Test the exact browser and content, or use a browser screenshot API.

Can I use it in a browser extension?

The project FAQ says not to use html2canvas in an extension and recommends the browser’s native extension screenshot API.