ScreenshotNeo

BlogHow-to

How to Fix Html2canvas Stalling After Rendering

Find where html2canvas stops, diagnose resources and canvas limits, and fix stalls with staged timing, CORS checks, sizing controls, and safer capture choices.

By the ScreenshotNeo team30 September 20268 min read

How to Fix Html2canvas Stalling After Rendering

When html2canvas appears to stall after rendering, first determine whether the html2canvas Promise has actually returned. The renderer logs Finished rendering before it returns the canvas. If that message appears, inspect the code that runs next—serialization, upload, image insertion, download, or a large UI update. If it does not appear, investigate cloning, resource loading, DOM parsing, and render work.

html2canvas reconstructs a page from DOM and CSS information; it does not take a native browser screenshot. Unsupported CSS, cross-origin resources, very large canvases, and repeated captures can therefore produce slow, blank, partial, or apparently frozen results.

1. Add a completion boundary and stage timing

Start with logging and a timer around the Promise. This separates html2canvas work from whatever your application does afterward.

async function capture(element) {
  console.time('html2canvas');

  const canvas = await html2canvas(element, {
    logging: true,
    onError: (error) => {
      console.warn('html2canvas resource failed:', error.message);
    },
  });

  console.timeEnd('html2canvas');
  console.log('canvas returned', {
    width: canvas.width,
    height: canvas.height,
  });

  return canvas;
}

Compare your own log with html2canvas’s Finished rendering message:

  • Both messages appear: the render completed. Instrument the next operation.
  • Your timer never ends: the Promise has not resolved. Continue with resource, dimension, clone, and render diagnostics.
  • The Promise resolves but the tab freezes: temporarily remove or time the next calls, such as toDataURL(), toBlob(), uploads, image insertion, or a large state update.

Do not assume that removeContainer fixes every stall. That option cleans up html2canvas’s temporary cloned DOM; it is a cleanup control, not a general hang remedy.

2. Reduce the problem to a minimal capture

Capture a small, static element before debugging a full page. If the small element succeeds, add sections back until the problematic content is isolated.

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

const canvas = await html2canvas(target, {
  logging: true,
  removeContainer: true,
});

Before calling html2canvas, record the target size and resource state:

console.table({
  clientWidth: target.clientWidth,
  clientHeight: target.clientHeight,
  scrollWidth: target.scrollWidth,
  scrollHeight: target.scrollHeight,
  devicePixelRatio: window.devicePixelRatio,
  images: document.images.length,
  fontsReady: document.fonts ? document.fonts.status : 'unsupported',
});

Wait for content your page controls, such as fonts or images, before starting the capture:

if (document.fonts?.ready) {
  await document.fonts.ready;
}

await Promise.all(
  [...document.images]
    .filter((img) => !img.complete)
    .map((img) => new Promise((resolve) => {
      img.addEventListener('load', resolve, { once: true });
      img.addEventListener('error', resolve, { once: true });
    }))
);

3. Check canvas dimensions, scale, and memory

Browser canvas limits vary by browser and platform. A canvas can be blank or partially rendered when its dimensions or area exceed what the platform supports, sometimes without a useful exception.

Reducing scale or splitting a long page can avoid oversized canvas output.
Reducing scale or splitting a long page can avoid oversized canvas output.

For long elements, the official FAQ documents using the element’s scroll dimensions as the rendering window:

const canvas = await html2canvas(element, {
  windowWidth: element.scrollWidth,
  windowHeight: element.scrollHeight,
});

The configuration reference also exposes scale, width, and height. scale defaults to the device pixel ratio. Lowering it is a practical diagnostic when a high-DPI capture becomes very large:

const canvas = await html2canvas(element, {
  scale: 1,
  width: Math.min(element.scrollWidth, 1600),
  height: Math.min(element.scrollHeight, 3000),
});

Use smaller regions or split a long page into sections when one canvas is too large. These changes reduce output dimensions and memory demand; they do not prove that size was the original cause.

4. Diagnose cross-origin images and redirects

By default, allowTaint is false. html2canvas skips images that would taint the canvas. To include a remote image, use useCORS: true only when the image server permits it with the required CORS response headers, or configure a proxy.

Cross-origin resources must pass browser CORS checks before html2canvas can draw them.
Cross-origin resources must pass browser CORS checks before html2canvas can draw them.
const canvas = await html2canvas(element, {
  useCORS: true,
  logging: true,
  onError: (error) => console.warn('Resource error:', error),
});

Inspect the browser Network panel for the final response after redirects, not only the URL in your HTML. A same-origin URL can redirect to a different host, where CORS rules apply. An individual GitHub issue describes this kind of report; it is not evidence of one universal bug or fix.

Browser security rules still apply: html2canvas cannot bypass cross-origin restrictions or read the contents of a cross-origin iframe. If a remote resource cannot send suitable CORS headers, use a server-side proxy you control or omit the resource.

5. Use the key html2canvas options deliberately

Option Use Diagnostic guidance
logging: true Enables debug logging. Keep it on while locating the last completed stage.
onError Receives notification when a resource fails to load or render; rendering continues. Log the message and inspect the failing request.
onclone Modifies the cloned document without changing the original DOM. Hide animations, video, or volatile elements in the clone.
removeContainer: true Removes the temporary cloned DOM after capture. Use for cleanup; do not treat it as a universal hang fix.
scale Controls output resolution; defaults to device pixel ratio. Lower it to reduce dimensions and memory.
windowWidth/windowHeight Sets the rendering window and can affect media queries. Use scroll dimensions for long targets when appropriate.
clearImageCache Releases shared image-cache memory in long-lived applications. Only consider it for repeated captures.
maxCacheSize Bounds the shared image cache. Choose a limit that fits your capture workload.

Do not clear an image cache shared by concurrent captures. Coordinate captures first, or keep cache management outside overlapping jobs.

6. Instrument clone work and animations

Use onclone to make the cloned page deterministic. This does not change the live page.

const canvas = await html2canvas(element, {
  logging: true,
  onclone: (clonedDocument) => {
    const style = clonedDocument.createElement('style');
    style.textContent = `
      *, *::before, *::after {
        animation: none !important;
        transition: none !important;
        caret-color: transparent !important;
      }
    `;
    clonedDocument.head.appendChild(style);
  },
});

If this changes the result, a moving or repeatedly reflowing element was contributing to inconsistent work. Hide expensive regions temporarily in the clone to isolate them:

await html2canvas(element, {
  onclone: (doc) => {
    doc.querySelectorAll('.live-chat, video, .ad-slot')
      .forEach((node) => { node.style.display = 'none'; });
  },
});

7. Check downstream serialization and upload

If the canvas has returned, test each subsequent operation independently. Large data URLs can consume substantial memory, while a Blob is generally a better upload boundary.

const canvas = await html2canvas(element);

console.time('toBlob');
const blob = await new Promise((resolve) => {
  canvas.toBlob(resolve, 'image/png');
});
console.timeEnd('toBlob');

if (!blob) throw new Error('Canvas could not be serialized');
console.log('blob bytes', blob.size);

const form = new FormData();
form.append('file', blob, 'capture.png');
await fetch('/upload', { method: 'POST', body: form });

For diagnosis, comment out upload, download, DOM insertion, and state updates one at a time. The html2canvas Promise boundary tells you whether the delay belongs to rendering or your application pipeline.

8. Decide whether html2canvas is the right capture method

html2canvas is useful when capture must run in the user’s page, but its DOM-derived output is not guaranteed to be pixel-identical to the browser. CSS support is limited to implemented properties, and cross-origin iframe contents remain inaccessible.

For a browser extension that needs the browser’s native tab image, the html2canvas FAQ points to chrome.tabs.captureVisibleTab() or browser.tabs.captureVisibleTab(). For server-side screenshots, the official material points to Puppeteer or Playwright, which drive a real headless browser.

9. Or skip the browser setup

If your goal is a reliable URL screenshot rather than an in-page DOM reconstruction, ScreenshotNeo returns a PNG, JPEG, WebP, or PDF from one GET request. Its cleanup steps accept cookie and consent banners, remove more than 60 known consent platforms plus newsletter popups and chat widgets, and each step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

See the complete option reference 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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
// Save bytes with your runtime's file API.

ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. It supports full-page and element captures, device presets, custom viewports, retina scale, waits, headers, cookies, user agents, authorization, blocking rules, custom CSS and JavaScript, caching, signed links, asynchronous jobs, webhooks, bulk capture, and a usage API.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free. Create a free ScreenshotNeo account.

10. Troubleshooting checklist

Symptom Likely boundary Fix
Finished rendering appears, then the UI freezes Serialization, upload, or state update Time toBlob, toDataURL, upload, and rendering separately.
Promise never resolves Clone, resource, DOM, or render stage Enable logging, add onError, reduce to a small element, and inspect network requests.
Canvas is blank or partial Canvas dimensions or unsupported content Lower scale, reduce width/height, or split the capture.
Images are missing CORS or failed resource load Use useCORS only with server permission, configure a proxy, and inspect redirects.
Repeated captures degrade Shared image cache or accumulated memory Bound maxCacheSize; use clearImageCache only when no capture is using the shared cache.
Cross-origin iframe is empty Browser security policy Capture the frame from its own origin or use a native/server-side browser workflow.
Output differs from the browser DOM reconstruction and CSS support Check supported properties and choose a real-browser capture when pixel fidelity matters.

11. Performance, reliability, and cost considerations

  • Performance: Smaller targets, lower scale, disabled animations, and ready resources reduce render work and memory.
  • Reliability: Record the html2canvas version, browser, platform, target dimensions, logs, network failures, and whether the completion boundary was reached.
  • Concurrency: Do not clear shared image caches while another capture is running.
  • Cost: html2canvas runs in the browser and has no service request cost, but it consumes the user’s CPU and memory. A hosted capture API adds request billing; ScreenshotNeo only bills clean shots and exposes X-Page-Verdict and X-Billed headers.

12. FAQ

Does removeContainer: true stop a hang?

No. It removes the temporary cloned DOM after capture. Use timing and logs to find the stage that is actually waiting.

Should I always set useCORS: true?

No. Set it when the remote image server sends the required CORS headers. Otherwise use a permitted proxy or omit the image.

Why does a smaller scale help?

It reduces the canvas’s pixel dimensions and memory demand. Treat that as a diagnostic and sizing choice, not proof of one universal browser limit.

Can html2canvas capture a cross-origin iframe?

No. Browser security restrictions prevent it from reading another origin’s document.

What information is needed to diagnose an unresolved case?

Provide the html2canvas version, browser and platform, a minimal reproduction, target dimensions, timing output, resource errors, and whether Finished rendering appears.