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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Insert or update the element first, wait for the browser to lay it out and for its images and fonts to become ready, then pass the actual element reference to html2canvas. The library captures the DOM state available at call time; it does not watch for future insertions or take a pixel-perfect screenshot of the browser.

Capture the element after it exists

In a client-side app, a newly created div can be captured once it has been inserted into the document. A practical sequence is: append the element, wait for a rendering frame, wait for relevant fonts and images, wait one more frame for any resulting layout changes, and call html2canvas(element).

Install the package with your project’s package manager:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
npm install @html2canvas/html2canvas

Here is a complete example for a dynamically created card. It returns a PNG data URL; replace that export step if you need a different delivery method.

#1 Best Overall
Sale
Epson Workforce ES-50 Compact & Lightweight Mobile Document Scanner
  • PORTABLE SCANNER FOR USE ON-THE-GO — The fastest and lightest mobile single-sheet-fed compact document scanner in its class¹
  • QUICK DOCUMENT SCANNING ― This Epson ultra-fast scanner scans a single page as quickly as 5.5 seconds²; Windows and Mac compatible
  • VERSATILE PAPER HANDLING ― Portable scanner scans documents up to 8.5 x 72 in; Also easily digitizes receipts and ID cards to make accounting, bookkeeping, and organizing simpler
  • INTUITIVE, HIGH-SPEED SOFTWARE — Epson ScanSmart Software³ is a smart tool allowing you to easily scan, review, and save; Stay organized easily with the help of this Epson scanner
  • EASY SETUP — USB-powered connect to your computer for quick and simple scanning; No batteries or external power supply required to operate portable document scanner; Standard Connectivity: USB 2.0
import html2canvas from '@html2canvas/html2canvas';

const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));

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

async function captureDynamicDiv() {
  const app = document.querySelector('#app');
  if (!app) throw new Error('Missing #app container');

  const card = document.createElement('div');
  card.id = 'capture-card';
  card.className = 'card';
  card.innerHTML = `
    <h2>New content</h2>
    <img src="/images/chart.png" alt="Chart">
  `;
  app.append(card);

  await nextFrame();
  if (document.fonts?.ready) await document.fonts.ready;
  await waitForImages(card);
  await nextFrame();

  const canvas = await html2canvas(card, {
    backgroundColor: '#fff',
    useCORS: true,
    onclone: clonedDoc => {
      clonedDoc.querySelectorAll('.capture-ignore').forEach(node => node.remove());
    }
  });

  return canvas.toDataURL('image/png');
}

captureDynamicDiv().then(pngUrl => {
  const preview = document.querySelector('#preview');
  if (preview) preview.src = pngUrl;
});

The selector #app and image path are examples: use elements and assets that exist in your application. The package’s documented installation and supported evergreen browsers are described in its getting-started documentation. The official examples use the same Promise-based capture and toDataURL() export pattern.

Why a newly added div may be missing

The call happens before insertion or framework rendering

If the code invokes html2canvas before the new node is added, or immediately after scheduling a framework state update that has not committed, the library can only render the earlier DOM. In React, Vue, or another framework, trigger capture from the appropriate post-render/update hook or after the update has completed. Pass the rendered element itself when possible instead of re-querying an ambiguous selector.

Rank #2
Sale
Brother DS-640 Compact Mobile Document Scanner, (Model: DS640)
  • FAST SPEEDS - Scans color and black and white documents a blazing speed up to 16ppm (1). Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • ULTRA COMPACT – At less than 1 foot in length and only about 1. 5lbs in weight you can fit this device virtually anywhere (a bag, a purse, even a pocket).
  • READY WHENEVER YOU ARE – The DS-640 mobile scanner is powered via an included micro USB 3. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan.
  • WORKS YOUR WAY – Use the Brother free iPrint&Scan desktop app for scanning to multiple “Scan-to” destinations like PC, Network, cloud services, Email and OCR. (2) Supports Windows, Mac and Linux and TWAIN/WIA for PC/ICA for Mac/SANE drivers. (3)
  • OPTIMIZE IMAGES AND TEXT – Automatic color detection/adjustment, image rotation (PC only), bleed through prevention/background removal, text enhancement, color drop to enhance scans. Software suite includes document management and OCR software. (4)

The element is present but not measurable

Check that the target is connected to the document, has non-zero width and height, and is not hidden with display: none. A hidden element may not have the layout dimensions required for a useful capture. A quick diagnostic is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const rect = card.getBoundingClientRect();
console.log({
  connected: card.isConnected,
  width: rect.width,
  height: rect.height,
  display: getComputedStyle(card).display
});

Images or fonts are still loading

Insertion does not mean every resource is ready. An image may have loaded but not finished decoding; a web font can change text wrapping and the card’s height after the first layout. Waiting for img.decode() and document.fonts.ready helps when those resources affect the result. The browser APIs define image decoding as readiness for use and font readiness as completion of font loading and layout work (image decode(); FontFaceSet.ready).

Rank #3
Sale
Epson Workforce ES-400 II High-Speed Color Duplex Desktop Document Scanner
  • FAST DOCUMENT SCANNING — Document scanner with feeder allows you to speed through stacks with a 50-sheet Auto Document Feeder (ADF); Efficient office scanner to help you scan more productively
  • INTUITIVE, HIGH-SPEED SOFTWARE — Quickly scan with this desktop document scanner; Epson ScanSmart Software lets you easily preview scans, email files, upload to the cloud, and more; Plus, automatic file naming saves even more time
  • SEAMLESS INTEGRATION — Easily incorporate your data into most document management software with the included TWAIN driver; Office document scanner integrates seamlessly with business workflows
  • EASY SHARING — Duplex scanner allows you to scan straight to email or popular cloud storage2 services like Dropbox, Evernote, Google Drive, and OneDrive for simple storage and sharing
  • SIMPLE FILE MANAGEMENT — Scanner allows the creation of searchable PDFs with Optical Character Recognition (OCR) and convert scans to editable Word or Excel files effortlessly; Designed for home and office document scanning

The requested result is not a browser screenshot

html2canvas reconstructs an image by reading DOM and styles; it does not capture the rendered screen pixel-for-pixel. Some CSS, plugin content, and content inside cross-origin iframes may therefore be unsupported or unavailable. Use it when client-side DOM reconstruction is acceptable. If the requirement is exact browser pixels or content that the page’s JavaScript cannot access, use a browser-level screenshot approach instead.

Waiting for insertion you do not control

When your own code creates the element, waiting inside the creation-and-capture function is usually clearest. If another component or script inserts it, use a MutationObserver to detect the target, then run the same readiness sequence. Disconnect the observer after finding the element, and debounce or otherwise coalesce repeated mutations so that a burst of DOM changes does not start many captures.

Rank #4
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
  • Scanner type: Document
  • Connectivity technology: USB
  • With Auto Scan Mode, the scanner automatically detects what you're scanning
  • Digitize documents and images

A repaint boundary is useful, but it is not a universal “everything is ready” signal. requestAnimationFrame() runs a one-shot callback before a repaint; awaiting one frame lets the browser process work after insertion. A second frame after image or font readiness allows the changed layout to settle. It does not replace explicit waits for asynchronous application data or resources.

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.

Options that affect dynamic captures

Pass options as the second argument to html2canvas(element, options). The project’s configuration reference documents these settings; choose only those that solve a specific capture need.

Best Value
Sale
ScanSnap iX2500 Wireless or USB High-Speed Document Scanner, Black
  • OUR MOST ADVANCED SCANSNAP. Large touchscreen, fast 45ppm double-sided scanning, 100-sheet document feeder, Wi-Fi and USB connectivity, automatic optimizations, and support for cloud services. Upgraded replacement for the discontinued iX1600
  • CUSTOMIZABLE. SHARABLE. Select personalized profiles from the touchscreen. Send to PC, Mac, mobile devices, and clouds. QUICK MENU lets you quickly scan-drag-drop to your favorite computer apps
  • STABLE WIRELESS OR USB CONNECTION. Built-in Wi-Fi 6 for the fastest and most secure scanning. Connect to smart devices or cloud services without a computer. USB-C connection also available
  • PHOTO AND DOCUMENT ORGANIZATION MADE EFFORTLESS. Easily manage, edit, and use scanned data from documents, receipts, photos, and business cards. Automatically optimize, name, and sort files
  • AVOIDS PAPER JAMS AND DAMAGE. Features a brake roller system to feed paper smoothly, a multi-feed sensor that detects pages stuck together, and skew detection to prevent paper damage and data loss
Option When it helps Important limit
onclone Modify the cloned document used for rendering, such as removing transient controls or disabling animation classes. Changes apply to the cloned capture document, not the live page. Use it for capture-only cleanup.
useCORS: true Attempt to load images from another origin when that server permits cross-origin use. The image server must send the required CORS headers; this option cannot override browser security policy.
proxy Load images through a same-origin proxy when direct cross-origin loading is unavailable. The proxy must be configured to retrieve and return the assets appropriately.
scale Control output resolution. The default follows the device pixel ratio; set a deliberate value for predictable output size. Higher scale increases canvas dimensions and memory use.
width, height, x, y Render a specified region or crop. Coordinates and dimensions must match the intended capture area.
windowWidth, windowHeight Set the rendering viewport, including when content exceeds the visible viewport. Large dimensions still encounter browser canvas and memory limits.
ignoreElements or data-html2canvas-ignore Exclude controls, handles, or overlays that should not appear in the output. Confirm the excluded elements are not part of the desired image.
imageTimeout Set how long html2canvas waits for images. The documented default is 15,000 ms; a longer wait can make a capture take longer without fixing a broken or blocked image.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Exporting and sizing the result

The example calls canvas.toDataURL('image/png'), which is convenient for a preview or small output. For large images, encoding a Blob with canvas.toBlob() can avoid placing a large base64 string in memory. For example:

const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
if (!blob) throw new Error('Canvas export failed');
const downloadUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = 'capture.png';
link.click();
URL.revokeObjectURL(downloadUrl);

Use a modest scale for long or complex content. A high device-pixel ratio multiplied by a large full-page area can create a very large canvas, use substantial memory, or exceed browser limits. If a long target clips or renders blank, inspect its measured dimensions and scroll dimensions, set the relevant viewport options, and reduce scale or split the content into smaller captures.

Troubleshooting checklist

  • Capture is blank or shows the old content: verify the target reference points to the inserted node, is still connected, and is captured after the framework’s render has committed.
  • The output is empty or clipped: check getBoundingClientRect(), display state, scroll dimensions, and the chosen viewport or crop settings. Reduce scale if the canvas is too large.
  • An image is missing: wait for load and decode; confirm its URL works; for cross-origin images use a server that permits CORS or a properly configured proxy.
  • Text wraps differently than expected: wait for document.fonts.ready before capture and allow a frame for layout to settle.
  • Only part of a dynamic update appears: await the application’s data or post-render completion before waiting for the repaint and calling html2canvas.
  • The result changes between captures: pause transitions or animations in onclone, and capture after the desired state has settled.
  • An iframe or plugin is absent: cross-origin and plugin restrictions prevent DOM reconstruction of some embedded content. Simplify the target or use a browser-level screenshot tool if the content must be captured.

Or skip the browser setup

If you need a hosted screenshot rather than a canvas made from your page’s DOM, ScreenshotNeo takes a URL in one GET request and returns an image or PDF. It is a different approach: it captures a page through a screenshot API rather than calling html2canvas on a local element.

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

cURL example, targeting a page you control:

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 API documentation for request parameters and response details. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots per month with no card, and paid plans start at $5 for 3,000. Sign up for free and try 1,000 screenshots a month with no card.

Frequently Asked Questions

Does html2canvas automatically capture a div added later?

No. Call it after the element has been inserted and is ready to render.

Can html2canvas capture an exact screenshot of a cross-origin iframe?

Not when browser origin restrictions prevent access to its contents; use a browser-level capture method if that content must be included.

Quick Recap

Bestseller No. 4
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Scanner type: Document; Connectivity technology: USB; With Auto Scan Mode, the scanner automatically detects what you're scanning
$75.00

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.

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.