October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Canvas API

How to Get Started with html2canvas: Browser Setup, Export, Options, and Fixes

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

The shortest path: install the html2canvas package in a browser JavaScript project, import it, select a real DOM element, and call html2canvas(element). The returned Promise resolves to a canvas that you can display or export as PNG. This is a DOM reconstruction, not a native screenshot of the browser’s pixels, so cross-origin images, unsupported CSS, iframes, and very large pages need special handling.

What html2canvas does (and does not do)

html2canvas walks through the document, reads element styles and content, and paints a representation onto an HTML <canvas>. The project describes it as taking “screenshots” of webpages or parts of them directly in the user’s browser. It does not copy the already-rendered pixel buffer. Every CSS feature must be implemented by the library, and the project does not support every CSS property.

That distinction determines whether it is a good fit:

  • Use it when a client-side canvas representation is enough and the page uses CSS and embedded content that html2canvas supports.
  • Do not expect guaranteed pixel identity with the browser, especially for unsupported CSS, browser-native controls, plugins, or cross-origin content.
  • For server-side rendering, use a real-browser tool such as Puppeteer or Playwright instead. For browser extensions, the browser’s native extension screenshot API avoids html2canvas’s canvas-size limits.

Install the package and prepare a browser project

The official getting-started material currently shows the scoped package @html2canvas/html2canvas for npm, Yarn, and pnpm. The npm package page and repository documentation also show the unscoped html2canvas name. Choose one package name and make the import match it; check the package’s current instructions when you install or upgrade.

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.

npm

npm install @html2canvas/html2canvas

Yarn or pnpm

yarn add @html2canvas/html2canvas

pnpm add @html2canvas/html2canvas

The examples below use the scoped package. If your project installed html2canvas instead, change the import to import html2canvas from 'html2canvas';. Run this code in a browser bundle or a module script after the target element exists; it is not a Node.js API.

First working capture

Create an element to capture, import the default function, and await the Promise it returns.

HTML

<button id="capture-button" type="button">Capture card</button>
<section id="capture">
  <h1>A card to capture</h1>
  <p>This content will be reconstructed on a canvas.</p>
</section>
<div id="result"></div>
<script type="module" src="/src/main.js"></script>

JavaScript

import html2canvas from '@html2canvas/html2canvas';

const button = document.querySelector('#capture-button');
const target = document.querySelector('#capture');
const result = document.querySelector('#result');

button.addEventListener('click', async () => {
  if (!target) return;

  try {
    const canvas = await html2canvas(target);
    result.replaceChildren(canvas);
  } catch (error) {
    console.error('Capture failed:', error);
  }
});

html2canvas(target) resolves asynchronously to a canvas. Appending that canvas lets you inspect the result immediately. Waiting for a button click is useful in an app because the DOM, fonts, images, and layout have had time to exist; in other code, call it after your render completes.

Export the canvas as a PNG

Once the Promise resolves, use the browser canvas API to create a data URL and trigger a download.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import html2canvas from '@html2canvas/html2canvas';

const target = document.querySelector('#capture');

async function downloadCapture() {
  if (!target) throw new Error('Missing #capture element');

  const canvas = await html2canvas(target);
  const link = document.createElement('a');
  link.download = 'capture.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
}

document.querySelector('#capture-button')
  .addEventListener('click', downloadCapture);

For a different image format, pass the format to toDataURL, provided the browser supports it. If a cross-origin image has tainted the canvas, export can throw a security error; fix the resource’s CORS configuration rather than trying to bypass it.

Useful capture options

Crop to a rectangle

Pass x, y, width, and height to capture a region rather than the whole selected element.

const canvas = await html2canvas(target, {
  x: 20,
  y: 10,
  width: 640,
  height: 360
});

These coordinates are capture options, not a way to read pixels outside what the browser can access.

Increase output density

Use a scale such as the device pixel ratio when you need a sharper image:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const canvas = await html2canvas(target, {
  scale: window.devicePixelRatio
});

Higher scale increases pixel dimensions and memory use. Test on the least capable device you support.

Exclude controls or overlays

Add data-html2canvas-ignore to anything that should not appear, such as a capture button or temporary status message.

<button data-html2canvas-ignore>Do not include me</button>

Handle remote images

useCORS: true asks the browser to load images using CORS:

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

This works only when the image server sends an appropriate Access-Control-Allow-Origin header. If it does not, route the image through a proxy that returns it from an origin your page can access. html2canvas cannot override browser content-security rules.

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

Reliable timing and layout

Capture after your application has finished rendering. Wait for data-driven components to update, fonts to load where relevant, and images to finish loading. A simple image wait can be useful for images already in the target:

await Promise.all(
  [...target.querySelectorAll('img')].map(img =>
    img.complete
      ? Promise.resolve()
      : new Promise(resolve => {
          img.addEventListener('load', resolve, { once: true });
          img.addEventListener('error', resolve, { once: true });
        })
  )
);
const canvas = await html2canvas(target);

This only waits; it does not make an inaccessible image safe to draw. Keep the target’s layout stable during capture so animations, responsive breakpoints, or late-loading content do not produce inconsistent output.

Diagnose common failures

Images from another origin are missing or export fails

Cause: the image server does not permit your page’s origin, so the canvas is tainted or the image is omitted.

Fix: configure the image server’s CORS response and use useCORS: true, or serve the resource through a same-origin proxy. Do not treat useCORS as a security bypass.

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

CSS looks different from the page

Cause: html2canvas reconstructs styles and only supports the CSS features implemented by the library.

Fix: check the project’s supported-features documentation for the property, simplify or replace unsupported styling, and test the exact browser targets you ship. Pixel-perfect output is not guaranteed.

The canvas is blank or cut off

Cause: browsers and operating systems impose implementation-dependent limits on canvas dimensions and total area. Oversized captures can be blank or partial without a useful error.

Fix: capture smaller sections, reduce scale, and set windowWidth and windowHeight to the element’s scroll dimensions when appropriate:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const canvas = await html2canvas(target, {
  windowWidth: target.scrollWidth,
  windowHeight: target.scrollHeight
});

There is no durable universal maximum; limits vary by browser, operating system, device, and available memory.

Nothing appears from an iframe

Same-origin iframes can be traversed recursively. Cross-origin frames cannot be rendered because the browser prevents access to their documents. A sandboxed frame without allow-same-origin has the same restriction.

A plugin or applet is absent

Plugin content such as Flash or Java applets is not rendered. Replace it with ordinary DOM content or use a native browser capture of the rendered page.

It works in the browser but not in Node.js

html2canvas depends on window, document, computed styles, and other browser APIs. It is not a server renderer. Run it in a browser, or use Puppeteer or Playwright to drive a real browser for server-side screenshots.

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

When to choose another screenshot method

Need Best direction Reason
Client-side canvas of a DOM element html2canvas Runs in the user’s browser and returns a canvas you control.
Server-side or automated native browser pixels Puppeteer or Playwright They drive a real browser rather than reconstructing the DOM.
Browser-extension capture Native extension screenshot API Avoids html2canvas’s canvas-size limits.
Remote screenshot API without browser setup ScreenshotNeo Clean shots, only clean shots billed, and the lowest paid plan.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools to Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for authentication and all options. This is a complete cURL example:

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

It also supports full-page lazy-image loading, CSS-selector element capture, dark mode, 12 device presets plus custom viewports, retina scale, PDF paper and page controls, HTML/CSS rendering, custom JavaScript and CSS, clicks before capture, selector hiding, selector/delay/network-idle waits, request and resource blocking, custom headers/cookies/user agents and Authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and familiar parameter names for easier migration.

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

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.

FAQ

Does html2canvas capture the entire webpage?

It captures the selected DOM element. Select a page container and account for its scroll dimensions, but split very large pages if canvas limits are reached.

Can I use html2canvas to capture a cross-origin iframe?

No. Browser same-origin rules prevent access to a cross-origin frame’s document.

Why is the function asynchronous?

It must traverse the DOM, resolve styles, load eligible resources, and paint the reconstructed result before returning the canvas.

Can I use the result in an image element?

Yes. Convert the canvas with toDataURL or toBlob, then assign the resulting URL to an image or upload the Blob.

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

Frequently Asked Questions

Does html2canvas capture the entire webpage?

It captures the selected DOM element. Select a page container and account for its scroll dimensions, but split very large pages if canvas limits are reached.

Can I use html2canvas to capture a cross-origin iframe?

No. Browser same-origin rules prevent access to a cross-origin frame’s document.

Why is the function asynchronous?

It must traverse the DOM, resolve styles, load eligible resources, and paint the reconstructed result before returning the canvas.

Can I use the result in an image element?

Yes. Convert the canvas with toDataURL or toBlob, then assign the resulting URL to an image or upload the Blob.

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

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.