ScreenshotNeo

BlogHow-to

How to Draw a Div to Canvas with html2canvas Without Timing Out

Prevent html2canvas timeouts by waiting for images and fonts, handling CORS, sizing tall elements correctly, and choosing safe capture settings.

By the ScreenshotNeo team30 September 20269 min read

How to Draw a Div to Canvas with html2canvas Without Timing Out

Direct answer: select the div, wait until its images and fonts are ready, then await html2canvas(element, options). Most hangs come from an image that never finishes, a cross-origin resource without CORS permission, or a capture viewport that is smaller than the element. Use a finite imageTimeout while diagnosing, set useCORS: true only when the image server sends a compatible header, and use the element’s scroll dimensions for a full-height capture.

import html2canvas from 'html2canvas';

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

  await document.fonts.ready;
  await Promise.all([...element.querySelectorAll('img')].map(async (img) => {
    if (img.complete) return;
    if (typeof img.decode === 'function') {
      try { await img.decode(); } catch (_) { /* handled by the timeout policy */ }
    } else {
      await new Promise(resolve => {
        img.addEventListener('load', resolve, { once: true });
        img.addEventListener('error', resolve, { once: true });
      });
    }
  }));

  const canvas = await html2canvas(element, {
    imageTimeout: 30000,
    useCORS: true,
    windowWidth: element.scrollWidth,
    windowHeight: element.scrollHeight,
    backgroundColor: '#ffffff',
    scale: Math.min(window.devicePixelRatio || 1, 2),
  });

  document.body.appendChild(canvas);
  return canvas;
}

drawDivToCanvas().catch(console.error);

The Promise returned by html2canvas resolves to a canvas. The configuration’s documented default for imageTimeout is 15,000 milliseconds; 0 disables that timeout. A zero timeout is useful as a diagnostic, but a resource that never resolves can then wait indefinitely. See the official configuration reference and FAQ.

1. Install html2canvas and make a minimal capture

Install the package in an application built with npm, or load it from a CDN. The npm version keeps the code under your normal dependency lockfile:

npm install html2canvas
<div id="capture">
  <h1>Invoice preview</h1>
  <img src="/assets/logo.png" alt="">
  <p>This entire element can be rendered to a canvas.</p>
</div>
<button id="save">Download PNG</button>
import html2canvas from 'html2canvas';

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

Capture the smallest useful element. Rendering document.body increases layout, paint, memory, and image work, and makes it harder to identify the resource that caused a timeout.

2. Wait for every asset that affects the result

Calling html2canvas immediately after inserting a component can capture a half-loaded state. Wait for web fonts and images first. document.fonts.ready waits for the browser’s font set to settle. img.decode() waits for an image to be decoded for painting where the browser supports it.

The reliable capture sequence waits for fonts and images before rendering the element.
The reliable capture sequence waits for fonts and images before rendering the element.
async function waitForImages(root) {
  const images = [...root.querySelectorAll('img')];
  await Promise.all(images.map(img => new Promise(resolve => {
    if (img.complete) return resolve();
    const done = () => resolve();
    img.addEventListener('load', done, { once: true });
    img.addEventListener('error', done, { once: true });
  })));

  // A loaded image can still be unusable (404, blocked, or empty).
  const failed = images.filter(img => !img.complete || img.naturalWidth === 0);
  if (failed.length) console.warn('Images failed or are empty', failed);
}

async function readyForCapture(root) {
  if (document.fonts?.ready) await document.fonts.ready;
  await waitForImages(root);
  // Let layout and a pending animation frame settle.
  await new Promise(requestAnimationFrame);
}

Pause carousels, blinking cursors, video overlays, and transitions during the capture. A temporary class is usually simpler than trying to reproduce an animation’s exact frame:

.capture-freeze *, .capture-freeze *::before, .capture-freeze *::after {
  animation: none !important;
  transition: none !important;
  caret-color: transparent !important;
}
const root = document.querySelector('#capture');
root.classList.add('capture-freeze');
try {
  await readyForCapture(root);
  const canvas = await html2canvas(root, { imageTimeout: 30000, useCORS: true });
  return canvas;
} finally {
  root.classList.remove('capture-freeze');
}

3. Fix image timeouts and cross-origin assets

html2canvas reconstructs a representation from the DOM and computed styles; it is not a native browser screenshot. Images loaded from another origin must satisfy browser content policy. useCORS: true requests CORS-enabled loading, but it cannot grant permission that the image server did not send. The server must return an appropriate Access-Control-Allow-Origin header.

If you control the asset server, configure that header and keep the image URL stable. If you do not, fetch the image through a same-origin proxy that you control, or copy it to your own origin. Do not expect html2canvas to bypass CORS. Cross-origin iframes are a separate hard limit: their contentDocument is inaccessible, so the iframe’s internal page cannot be rendered by this library.

const canvas = await html2canvas(element, {
  useCORS: true,
  imageTimeout: 30000,
  proxy: '/image-proxy',
});

Use either a correctly configured CORS response or a same-origin proxy according to your architecture. A proxy that silently returns an HTML error page instead of an image will still fail; inspect its status, content type, and final URL.

4. Capture a full-height div without clipping

The visible viewport is often shorter than a long card. Give html2canvas the element’s scroll dimensions:

const element = document.querySelector('#capture');
const canvas = await html2canvas(element, {
  windowWidth: element.scrollWidth,
  windowHeight: element.scrollHeight,
  width: element.scrollWidth,
  height: element.scrollHeight,
  x: 0,
  y: 0,
});

If the element is inside a scroll container, temporarily remove the container’s clipping or set its height to the content height while capturing. A child with overflow: hidden can still be intentionally clipped; increase its dimensions only when the full content is required. For a viewport-sized capture of a very large document, cullOffscreen: true can reduce work. Use it carefully when off-screen content has layout-dependent effects.

5. Choose options deliberately

Option Use it for Important behavior
imageTimeout Bounding image waits Default is 15,000 ms; 0 disables the timeout.
useCORS Remote images with server CORS Requires the response’s CORS header; it does not bypass browser policy.
proxy Same-origin image retrieval Use a proxy you operate and validate its responses.
windowWidth/windowHeight Full-width or full-height layout Set from scrollWidth/scrollHeight for a tall element.
scale Output sharpness Defaults to window.devicePixelRatio; higher values multiply pixels and memory.
backgroundColor Opaque output Set a color, or use null when transparency is required.
ignoreElements Exclude controls or unstable widgets Return true for nodes that should not be cloned.
data-html2canvas-ignore Declarative exclusions Add the attribute to buttons, toolbars, or debug elements.
removeContainer Cleanup after rendering The documented default is true.
allowTaint Special image policies A tainted canvas cannot be read with toDataURL or pixel APIs; CORS or a proxy is safer.
const canvas = await html2canvas(element, {
  scale: 1.5,
  backgroundColor: null,
  ignoreElements: node => node.matches('.no-print, button'),
  logging: true,
  imageTimeout: 20000,
});

6. Complete reusable capture function

import html2canvas from 'html2canvas';

export async function captureElement(selector, {
  timeout = 30000,
  scale = Math.min(window.devicePixelRatio || 1, 2),
  fullHeight = true,
} = {}) {
  const element = document.querySelector(selector);
  if (!element) throw new Error(`No element matches ${selector}`);

  if (document.fonts?.ready) await document.fonts.ready;
  await Promise.all([...element.querySelectorAll('img')].map(img => {
    if (img.complete) return Promise.resolve();
    return new Promise(resolve => {
      img.addEventListener('load', resolve, { once: true });
      img.addEventListener('error', resolve, { once: true });
    });
  }));

  const width = element.scrollWidth;
  const height = element.scrollHeight;
  return html2canvas(element, {
    imageTimeout: timeout,
    useCORS: true,
    scale,
    windowWidth: fullHeight ? width : window.innerWidth,
    windowHeight: fullHeight ? height : window.innerHeight,
    width: fullHeight ? width : undefined,
    height: fullHeight ? height : undefined,
    logging: false,
  });
}

const canvas = await captureElement('#capture');
const png = canvas.toDataURL('image/png');

7. Troubleshooting checklist

It waits until the timeout

Open DevTools Network and identify requests still pending or repeatedly failing. Check image URLs, redirects, DNS, authentication, and response content types. Fix the resource first; increasing the timeout only helps a slow but valid response.

Images are blank or the canvas is tainted

The image is cross-origin without compatible CORS headers, or it was loaded before the CORS mode was applied. Serve it with Access-Control-Allow-Origin, use a same-origin proxy, and set useCORS: true. If you need to export pixels, do not rely on a tainted canvas.

The output is empty or clipped

Capture the actual element, not a selector that resolves to a hidden node. Set windowWidth and windowHeight from scroll dimensions, and inspect ancestor overflow rules. The html2canvas FAQ specifically recommends scroll dimensions for empty or clipped output.

Web fonts change after capture

Await document.fonts.ready, then allow one animation frame for layout. Confirm the font request succeeded and that the CSS uses the intended weight.

An iframe is missing

A cross-origin iframe cannot be read by browser JavaScript. Capture content you own from inside that origin, replace it with a same-origin representation, or use a browser-level screenshot service.

Repeated captures slow the page

Large canvases consume substantial memory. Reuse or release references, remove temporary canvases, avoid unnecessarily high scale, and capture only the required region. Keep removeContainer enabled unless you have a specific reason to inspect the cloned container.

8. Performance, reliability, and cost considerations

  • Pixel count: canvas memory grows with width × height × scale². A two-times scale has roughly four times as many pixels as a one-times scale.
  • Network work: fewer images, smaller images, and a warm browser cache reduce capture time. Lazy-loaded images may need to be scrolled into view or explicitly loaded before capture.
  • Timeout policy: keep a finite timeout in production so one broken URL cannot hold a request forever. Use 0 only when an intentionally indefinite wait is acceptable.
  • Repeatability: freeze animations, wait for fonts, and use deterministic data. Record failed image URLs so a support report identifies the actual dependency.
  • Security: a same-origin proxy should allow only approved destinations, enforce response-size limits, and avoid forwarding sensitive cookies to arbitrary hosts.

html2canvas runs in the browser and has no separate per-capture service charge. Your costs are the user’s browser resources and any infrastructure used for a proxy or asset hosting. For server-side, API-based capture, the browser setup and its CORS limits can be removed entirely.

A server-side capture can clean consent banners and transient widgets before delivery.
A server-side capture can clean consent banners and transient widgets before delivery.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF. Its capture flow accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether it was billed.

See the ScreenshotNeo API documentation for all options. The same request works from a shell:

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,
)
r.raise_for_status()
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));

ScreenshotNeo also supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, caching with a chosen TTL, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Its parameter names also work with those used by other screenshot APIs, which helps when switching.

An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients, so an AI agent can capture pages without custom browser automation. Pricing starts with 1,000 shots per month free with no card; paid plans start at $5 for 3,000 shots. Other plans are $15 for 15,000, $39 for 60,000, $99 for 250,000, and $249 for 1,000,000; yearly billing gives two months free, and every feature is on every plan.

Create a free ScreenshotNeo account and get 1,000 screenshots each month with no card.

FAQ

Should I set imageTimeout to zero?

Only when you intentionally accept an indefinite wait. A finite value exposes broken resources and lets your application recover.

Does useCORS fix every external image?

No. The remote server must send a compatible CORS header. Otherwise use a same-origin proxy or host the asset on your origin.

Can html2canvas capture a complete cross-origin page?

No. Cross-origin iframe documents are inaccessible, and cross-origin images need CORS or a proxy.

Why is my tall div cut off?

Use element.scrollWidth and element.scrollHeight for the capture viewport and check ancestor overflow rules.

What scale should I use?

Start near 1 or the device pixel ratio capped at 2, then increase only when the output needs more detail. Higher scale increases memory and processing time.