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

html2canvas turns a DOM element into a <canvas> asynchronously in a browser. Install the package, select the element, await the returned Promise, then display or export the canvas. It reconstructs the image from the DOM and styles it can read; it does not copy the browser’s already-rendered pixels, so unsupported CSS, cross-origin images, and very large elements can produce differences or incomplete output.

What html2canvas actually does

html2canvas walks an element’s DOM tree, reads computed styles and resources, and draws its own representation onto a canvas. The project documentation describes the result this way: “The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.”

That distinction determines when to use it. It is useful when a page itself needs to offer an export button, when you want to capture a component without leaving the browser, or when you need a canvas for further processing. It is not a pixel-level browser screenshot API. CSS properties that html2canvas has not implemented, browser-native UI, some generated content, and resources blocked by browser security rules may not appear as they do on screen.

Install and make a minimal capture

Package installation

The official getting-started guide lists the html2canvas package and package-manager installs. Choose one command in your project directory:

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.
  • npm install html2canvas
  • yarn add html2canvas
  • pnpm add html2canvas

The current guide targets modern evergreen browsers, including Chrome/Chromium-based browsers, Firefox, and Safari. The library depends on browser APIs such as window, document, layout information, and computed styles.

Smallest working example

import html2canvas from 'html2canvas';

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

const canvas = await html2canvas(element);
document.body.appendChild(canvas);

Place an element with id="capture" in the page. Because the function returns a Promise, the code must run inside an async function or another context that permits await. The resolved value is a normal canvas, so you can append it, draw it elsewhere, or encode it.

Export as a downloadable PNG

async function downloadCapture() {
  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 = 'capture.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
}

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

Keep the export operation after the Promise resolves. Calling toDataURL() before rendering finishes will not produce the intended image.

Options that matter in real pages

Pass an options object as the second argument: html2canvas(element, options). The most useful settings address image loading, viewport dimensions, and output scale.

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

Cross-origin images: useCORS and proxies

Images loaded from another origin are subject to the browser’s same-origin policy. If a remote image is drawn without permission, the canvas can become “tainted”; reading it with toDataURL() or getImageData() then fails.

const canvas = await html2canvas(element, {
  useCORS: true
});

useCORS: true is effective only when the image server sends a suitable Access-Control-Allow-Origin response header. It does not bypass browser security. If you control the image host, configure that header and ensure the image request is made in a CORS-compatible way. Otherwise, use a server-side proxy that fetches the resource and returns it in a form your page can legally load. A proxy must be configured correctly; merely relaying a URL does not remove the 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.

For a quick diagnosis, temporarily remove remote images or replace them with same-origin assets. If the canvas becomes readable, inspect the image responses and CORS headers rather than changing unrelated rendering options.

Long or clipped elements

Canvas dimensions have browser- and device-dependent limits. An oversized capture may be blank, partially rendered, or cut off even though a small element works. The FAQ recommends matching windowWidth and windowHeight to the element’s scroll dimensions when a long page needs a larger layout viewport:

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.
const canvas = await html2canvas(element, {
  windowWidth: element.scrollWidth,
  windowHeight: element.scrollHeight
});

Those values are not a universal safe maximum. Test the target browsers and devices, and split a very large document into sections when a single canvas approaches platform limits. A tiled workflow—capture several smaller elements and combine them—usually fails less dramatically than one enormous canvas.

Choosing the element and preparing it

  • Select the smallest container that includes exactly the content you need; capturing the whole document increases memory use.
  • Wait until fonts, images, and asynchronous component data have finished loading before calling html2canvas.
  • Use a temporary capture class to set a stable background, remove animations, and reveal content that is intentionally hidden during normal interaction.
  • Restore any temporary styles after the Promise resolves, including in a finally block if the capture can fail.

Scale, transparency, and output format

Canvas pixels and the displayed CSS size are separate. If you need a higher-density export, use the library’s scale option within the memory limits of the target device:

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

A transparent background can be requested with backgroundColor: null when the design requires alpha; otherwise choose an explicit color so transparent areas do not become unexpected black or checkerboard regions in downstream tools. Encode with canvas.toDataURL('image/jpeg', 0.9) for JPEG, or keep PNG for transparency and crisp text. Higher scale multiplies pixel count, memory use, and encoding time.

What will differ from the live page

Every CSS property needs an implementation in html2canvas to render correctly; the project FAQ states that it “will never have full CSS support.” Differences are therefore expected, not necessarily bugs in your code.

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.
  • Check the project’s supported-features documentation when a property such as a filter, blend mode, advanced clipping, or a particular generated effect is missing or altered.
  • Reduce the page to a minimal element and one style at a time. This identifies whether layout, font loading, an image, or an unsupported property causes the mismatch.
  • Compare in each browser you intend to support. Font availability, device pixel ratio, and native rendering can change the result.
  • Do not assume browser chrome, scrollbars, video frames, or content rendered outside the DOM will be reproduced.

The official examples page provides a side-by-side HTML/CSS editor and output preview; it is useful for learning which visual constructs are reconstructed rather than captured as pixels.

Browser support and runtime boundaries

Supported browser context

Use html2canvas in a modern browser page where the DOM and styles are available. Test the exact evergreen browser versions your application supports, especially when exports are part of a customer workflow.

Why Node.js does not work directly

html2canvas is client-side software. A Node.js process has no real window, document, layout engine, or browser-computed styles, so importing it in a server script is not a server screenshot solution. For server-side captures, the official FAQ names Puppeteer and Playwright, which drive a headless browser. Those tools render a page in an actual browser context and are a different architecture from html2canvas.

Browser extensions

For an extension, the FAQ recommends the browser’s native extension screenshot APIs as the more reliable choice for that environment. They capture browser-rendered content rather than asking a page script to reconstruct it.

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

A practical capture workflow

  1. Define the boundary. Add a stable ID or selector around the component to export.
  2. Wait for readiness. Confirm data, images, fonts, and any layout-changing animations are complete.
  3. Check asset origin. Make images same-origin, configure valid CORS headers, or use a correctly configured proxy.
  4. Capture asynchronously. Await html2canvas(element, options) and handle rejection.
  5. Inspect before encoding. Append the canvas temporarily or inspect its dimensions to catch clipping.
  6. Encode and deliver. Use toDataURL() for a simple download or toBlob() for a more memory-friendly file workflow.
  7. Test limits. Repeat with the longest content and the smallest supported device, not just a short desktop example.
async function renderCard() {
  const element = document.querySelector('#card');
  if (!element) throw new Error('Missing #card');

  const oldClass = element.className;
  element.classList.add('capture-mode');
  try {
    const canvas = await html2canvas(element, {
      useCORS: true,
      scale: Math.min(window.devicePixelRatio || 1, 2),
      backgroundColor: '#fff'
    });

    const blob = await new Promise((resolve, reject) =>
      canvas.toBlob(file => file ? resolve(file) : reject(new Error('Encoding failed')), 'image/png')
    );
    return blob;
  } finally {
    element.className = oldClass;
  }
}

Troubleshooting by symptom

“My images are missing”

Confirm that the image URL is reachable, the image has finished loading, and its server sends an appropriate CORS header. Add useCORS: true only for a server that actually permits the request. If you cannot change the server, use a properly configured proxy or move the asset to an origin you control.

“The canvas cannot be read” or a security exception appears

This usually indicates a tainted canvas caused by cross-origin image data. Remove images to verify the cause, then fix the response headers or proxy path. No html2canvas option can override the browser’s security 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

“The output does not match the page”

Look for CSS that the library does not implement, fonts that were not ready, animations captured mid-frame, and browser-specific layout. Consult the supported-features documentation and reproduce the smallest failing element.

“A long capture is blank or cut off”

Measure the element’s scroll dimensions, try matching windowWidth and windowHeight, lower the scale, and split the capture if necessary. Browser and device canvas limits vary, so do not rely on one maximum dimension.

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

“It works on desktop but not on a phone”

Reduce width and scale, test the real mobile browser, and avoid one canvas containing an entire long document. Mobile memory and canvas limits can be lower than desktop limits.

“Nothing happens when I click Export”

Check the browser console for a rejected Promise, verify the selector is non-null, and ensure the handler is async or explicitly chains .then(). Also make sure the download is initiated from the user gesture where browser download policies require it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

When you need a clean website screenshot rather than a DOM reconstruction, ScreenshotNeo makes one GET request and returns PNG, JPEG, WebP, or PDF. It accepts the cookie or consent banner like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether it was billed.

For a quick capture, see the ScreenshotNeo API documentation and run:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

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)

Node.js

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 also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Its 63 options include full-page captures with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets plus custom viewports, retina scale, PDF paper and page controls, custom CSS and JavaScript, click-before-capture, hide selectors, selector/delay/network-idle waits, ad and tracker blocking, custom headers/cookies/user agents/Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed public image links, asynchronous jobs with signed webhooks, bulk capture of 100 URLs per call, a usage API, an OpenAPI specification, and familiar parameter names for easier migration.

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.

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

html2canvas or a browser screenshot service?

Question html2canvas Browser screenshot service or headless browser
Where it runs Inside the user’s browser In a service or browser process you control
What is rendered A reconstruction from DOM and supported styles The browser’s rendered view
Remote images Subject to same-origin and CORS rules Controlled by the capture environment and its network policy
Best fit Client-side export of a component Automated, server-side, full-page, or high-fidelity captures

Choose html2canvas when the export belongs in the page and its reconstruction limits are acceptable. Choose a headless-browser approach or a service when you need server execution, full-page automation, or the pixels a browser actually rendered.

FAQ

Does html2canvas take a real screenshot?

No. It builds a canvas from DOM and style information, so visual differences are possible.

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

Can I use it without a framework?

Yes. It only needs a browser page, a selected element, and the installed JavaScript package; React, Vue, or another framework is not required.

Should I use the scoped @html2canvas/html2canvas package instead?

The available package listing describes that name as a fork, but the reviewed materials do not establish a replacement policy or migration path. Follow the current official project and package guidance rather than assuming the names are interchangeable.

Frequently Asked Questions

Can html2canvas capture content hidden with CSS?

It can only reproduce what its DOM and style traversal can resolve. Temporarily applying a capture-specific class that makes required content visible is more predictable than relying on elements that are permanently detached or unavailable to layout.

What is the safest way to process a large result?

Capture smaller sections when possible, keep scale modest, and use toBlob() instead of a large data URL when handing the image to application code.

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

Is a proxy required for every external image?

No. A proxy is needed only when the image cannot be served with suitable CORS permission from its host and you still need that cross-origin image in a readable canvas.

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.