Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
Canvas API

How to Take Screenshots with html2canvas (Browser, CORS, Full-Page and Export Guide)

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

html2canvas captures a DOM element by rebuilding it in a canvas inside the browser. Install @html2canvas/html2canvas, select an element, call html2canvas(element, options), then export the returned canvas with toDataURL() or toBlob(). It is not a pixel-perfect operating-system screenshot: unsupported CSS, cross-origin assets and very large canvases can change or prevent the result.

What html2canvas actually captures

The html2canvas project describes its script as allowing “screenshots” of webpages or parts of them directly in a user’s browser. The quotation marks matter. The library traverses the DOM, reads styles and redraws supported content. It does not ask the browser or operating system for the final composited pixels.

  • Runs client-side: it depends on browser APIs and is intended for code running in a page.
  • Reconstruction has limits: CSS properties, filters, embedded documents and browser-specific rendering may differ from the live page.
  • Security still applies: cross-origin images and frames cannot be used to bypass browser origin policy.

For a browser extension or a server-rendered capture, use the browser’s native extension screenshot API or a headless browser such as Puppeteer or Playwright instead.

Install and make a basic PNG

Install from npm

npm install @html2canvas/html2canvas

With Yarn, use yarn add @html2canvas/html2canvas; with pnpm, use pnpm add @html2canvas/html2canvas. You can also load a built release in a browser page, but bundling the package keeps dependency management explicit.

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

Minimal browser example

import html2canvas from '@html2canvas/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();

Call this from an event handler or another function after the target has rendered. The Promise resolves to a <canvas>. If you are using a script tag rather than a module, call the globally exposed html2canvas function after loading the built release.

Control quality, size and the captured region

Pixel density with scale

The default scale is the browser’s window.devicePixelRatio. A high-density display therefore produces a larger canvas. Lower it to reduce memory use, or raise it for sharper output when the element is modest in size.

const canvas = await html2canvas(document.querySelector('#capture'), {
  scale: 1.5,
  backgroundColor: '#ffffff'
});

Increasing scale multiplies both pixel count and memory pressure. Test the largest target devices you support rather than assuming a setting is safe everywhere.

Crop with coordinates

Use x, y, width and height to render a region. Coordinates are interpreted against the document view used for rendering.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
const canvas = await html2canvas(document.body, {
  x: 100,
  y: 200,
  width: 800,
  height: 500,
  scale: 1
});

Transparent or custom backgrounds

If the source has no background, html2canvas defaults to white. Set backgroundColor: null for transparency, or provide a CSS color for a predictable opaque result.

const canvas = await html2canvas(document.querySelector('#logo-card'), {
  backgroundColor: null
});

Viewport and scrolling

windowWidth and windowHeight control the viewport used while styles and media queries are evaluated. scrollX and scrollY let you reproduce a particular scroll position, which is important for fixed-position elements.

Capture a full element or a long page

For an element that extends beyond the viewport, measure its scroll dimensions and pass them as the rendering viewport:

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

This can still fail. Canvas maximum dimensions and total pixel-area limits vary by browser, operating system and available memory. The html2canvas FAQ gives approximate examples observed in 2026: Chrome/Chromium and desktop Safari around 32,767 pixels for a maximum dimension, Firefox around 32,767 pixels, and roughly 268 megapixels for Chromium versus roughly 472 megapixels for Firefox. These are not cross-browser guarantees; iOS Safari can be lower and depends on device RAM.

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.
  • Capture sections separately when a page is taller than a safe canvas.
  • Reduce scale before reducing CSS dimensions that affect layout.
  • Check for a blank or partially rendered canvas even when no exception is thrown.
  • Run tests on the browsers and devices where users will create images.

Keep controls and transient UI out of the image

Ignore an element with an attribute

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

The element is omitted from the reconstructed canvas.

Ignore elements with a predicate

const canvas = await html2canvas(document.querySelector('#capture'), {
  ignoreElements: element => element.matches('.no-screenshot, [aria-hidden="true"]')
});

Change the cloned page with onclone

Use onclone to modify the temporary document without changing what the visitor sees:

const canvas = await html2canvas(document.querySelector('#capture'), {
  onclone: clonedDocument => {
    clonedDocument.querySelectorAll('.editing-toolbar')
      .forEach(node => node.remove());
  }
});

Cross-origin images, frames and tainted canvases

Images loaded from another origin are subject to normal browser CORS rules. With the default allowTaint: false, resources that would taint the canvas are skipped. Setting useCORS: true asks the browser to load images with CORS, but it succeeds only when the image server returns an appropriate Access-Control-Allow-Origin response.

const canvas = await html2canvas(document.querySelector('#capture'), {
  useCORS: true
});

If you control the asset server, configure it to permit the requesting origin and ensure the image is requested in a way compatible with that policy. An optional proxy can fetch an image through a same-origin endpoint:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
const canvas = await html2canvas(document.querySelector('#capture'), {
  proxy: '/image-proxy',
  useCORS: true
});

A proxy must be your own correctly secured service; it is not a way to defeat access controls. Never create an open proxy that lets arbitrary users fetch internal network addresses. A canvas containing disallowed cross-origin content cannot be safely read or exported, so fixing the response headers or removing the asset is preferable to trying to export a tainted canvas.

Export PNG, JPEG or a Blob

PNG download

const canvas = await html2canvas(document.querySelector('#capture'));
canvas.toBlob(blob => {
  if (!blob) throw new Error('Image encoding failed');
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = 'capture.png';
  link.href = url;
  link.click();
  URL.revokeObjectURL(url);
}, 'image/png');

JPEG with quality

const canvas = await html2canvas(document.querySelector('#capture'));
const jpeg = canvas.toDataURL('image/jpeg', 0.85);
const link = document.createElement('a');
link.download = 'capture.jpg';
link.href = jpeg;
link.click();

PNG preserves transparency and is lossless. JPEG is usually smaller for photographic content but has no transparency and introduces compression artifacts. For large images, toBlob() avoids placing the entire encoded file in a long data URL.

Why CSS or content looks wrong

Unsupported or partially supported CSS

Because html2canvas redraws supported properties rather than taking final pixels, complex filters, blend modes, advanced clipping, generated content, some form controls and embedded documents may differ. Reduce the design to supported primitives for a dependable export, or use a browser screenshot API when exact visual fidelity is required.

Fonts and asynchronous content

Wait until web fonts, images and data-driven components have finished rendering before calling the library. A practical pattern is to trigger capture after your own loading state is complete and, where needed, wait for image elements:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await Promise.all([...document.images].map(image => {
  if (image.complete) return Promise.resolve();
  return new Promise(resolve => {
    image.addEventListener('load', resolve, { once: true });
    image.addEventListener('error', resolve, { once: true });
  });
}));
const canvas = await html2canvas(document.querySelector('#capture'));

Fixed elements and scroll position

Fixed headers can appear at the viewport position rather than where you expect in a long capture. Set scrollX and scrollY, or temporarily alter the cloned document with onclone.

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

Troubleshooting checklist

  • “Images are missing”: inspect the image response for CORS headers; try useCORS: true, a controlled proxy, or same-origin hosting.
  • “The canvas is empty or cuts off halfway”: check scroll dimensions, lower scale, split the capture, and test another browser. Oversized canvases can fail without an exception.
  • “CSS renders only partially”: identify unsupported effects and replace them for export, or switch to browser-native capture.
  • “It does not work in Node.js”: html2canvas is client-side. Use Puppeteer or Playwright to drive a headless browser.
  • “The result includes buttons or popups”: mark them with data-html2canvas-ignore, use ignoreElements, or remove them in onclone.
  • “Text is blurry”: increase scale within memory limits, ensure fonts have loaded, and avoid repeatedly resizing an already encoded image.

When html2canvas is the wrong tool

Need Better fit Reason
Capture a page from JavaScript running in that page html2canvas No server browser is required, but output is a DOM reconstruction.
Browser extension screenshot Native extension screenshot API The html2canvas FAQ recommends native APIs and warns against using html2canvas in extensions.
Server-side or automated capture Puppeteer or Playwright They drive a browser runtime and can capture rendered pixels without relying on a page’s own script.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. It returns PNG, JPEG, WebP or PDF from one request and is useful when captures must run outside a user’s browser. Cookie and consent banners, newsletter popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are not billed. Responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

Use the ScreenshotNeo API documentation for all options. A direct cURL request:

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

There is a free allowance of 1,000 screenshots each month without a card. Paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

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

Frequently Asked Questions

Can html2canvas capture an iframe from another origin?

Not reliably. The browser’s same-origin policy prevents reading another origin’s document. Capture content you control in the same origin or use a browser automation workflow with appropriate access.

Does html2canvas produce a PDF?

It produces a canvas. Convert that image with a separate PDF library, or use a browser automation or screenshot API that supports PDF output directly.

Can I capture an element before it is visible?

The element must have renderable layout and styles in the cloned document. Hidden elements generally need to be made visible in the clone with onclone or captured after they are displayed.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.