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 DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
Canvas

How to Capture Images Inside a Div With html2canvas

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.

Pass the actual DOM element to html2canvas(), wait for its Promise, and export the returned canvas. The smallest working example is:

const element = document.querySelector('#capture');
const canvas = await html2canvas(element);
document.body.appendChild(canvas);

html2canvas rebuilds the selected element from its DOM and CSS in the browser; it does not take a pixel-for-pixel operating-system screenshot. That distinction explains most differences, missing images and unsupported-style problems.

Capture a div and display the result

Load html2canvas in your page, give the target a stable selector, then pass the resolved element—not the selector string—to the function. Because the function is asynchronous, use await inside an async function or handle the returned Promise.

<button id="capture-button" type="button">Capture card</button>
<div id="capture" class="card">
  <h2>Monthly report</h2>
  <p>Revenue increased 18% this month.</p>
</div>
<script src="/vendor/html2canvas.min.js"></script>
<script>
  document.querySelector('#capture-button').addEventListener('click', async () => {
    const element = document.querySelector('#capture');
    if (!element) throw new Error('The #capture element was not found');

    const canvas = await html2canvas(element);
    document.body.appendChild(canvas);
  });
</script>

The Promise resolves to an HTML <canvas>. Appending that canvas is useful while you tune the capture; production code normally converts it to a downloadable file or uploads it.

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.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Promise syntax without async/await

html2canvas(document.querySelector('#capture')).then(canvas => {
  document.body.appendChild(canvas);
}).catch(error => {
  console.error('Capture failed', error);
});

Save the div as a PNG

The canvas API can produce a PNG data URL. Create a temporary anchor, assign the URL, and trigger it:

async function downloadDivAsPng() {
  const element = document.querySelector('#capture');
  if (!element) return;

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

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

toDataURL() keeps the complete image in memory as a string, so a very large result can consume substantial memory. For large captures, convert the canvas with toBlob() and create an object URL instead:

function canvasToDownload(canvas, filename = 'capture.png') {
  canvas.toBlob(blob => {
    if (!blob) throw new Error('The browser could not encode the canvas');
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.download = filename;
    link.href = url;
    link.click();
    URL.revokeObjectURL(url);
  }, 'image/png');
}

html2canvas(document.querySelector('#capture')).then(canvas => {
  canvasToDownload(canvas);
});

Control resolution, crop and background

Options are passed as the second argument. These are the settings most often needed for a div capture:

Option Purpose Practical use
scale Controls output pixel density; the default is window.devicePixelRatio. Use 1 for a smaller file or set 2 for sharper retina-style output. Higher values increase memory use.
x, y, width, height Defines a crop/render region. Useful when capturing a subsection or avoiding surrounding whitespace.
backgroundColor Sets the canvas background. Use null for transparency; otherwise an unspecified DOM background defaults to white.
windowWidth, windowHeight Changes the virtual viewport used while rendering. Set dimensions deliberately when media queries or responsive layout affect the div.
data-html2canvas-ignore Marks an element to omit. Add the attribute to buttons, selection handles or other controls that should not appear.
ignoreElements Receives a predicate and skips matching nodes. Use JavaScript when the elements to hide are dynamic.
useCORS Attempts to load images with cross-origin requests. Works only when the image server permits the request with suitable CORS headers.
proxy Routes image loading through a proxy. Use a server you control when remote images cannot provide CORS permission.

Example: transparent, high-resolution card

const canvas = await html2canvas(document.querySelector('#capture'), {
  scale: 2,
  backgroundColor: null,
  windowWidth: 1200,
  windowHeight: 900,
  ignoreElements: element => element.matches('.no-export')
});

Choose the scale before exporting. A scale of 2 doubles each dimension and therefore produces about four times as many pixels as scale 1; it is not a free quality improvement.

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

Make the capture reflect the final state

Wait for fonts, images and application data

Call html2canvas only after the content you want is present. In an app that loads data asynchronously, wait for the request and render update first. For web fonts, wait for document.fonts.ready where supported. For individual images, wait for their load events before capturing. A timeout alone is less reliable because network and device speed vary.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
await document.fonts.ready;
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'));

Capture a hidden or scrollable component

An element with display: none has no layout for html2canvas to render. Temporarily move it into a visible, positioned container, capture it, then restore the styles. For content clipped by a scroll box, capture the element’s full scroll dimensions or pass explicit width and height; set windowWidth and windowHeight to matching values when responsive rules are causing a cut-off result.

Remove controls only from the image

Prefer data-html2canvas-ignore for static exclusions:

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

For a rule-based exclusion, use ignoreElements as shown above. This changes only the rendered clone, not the live page.

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

Know what html2canvas can and cannot reproduce

The library parses the DOM and supported CSS properties, then paints an approximation into a canvas. It is not a literal browser compositor capture. Complex or unsupported CSS, browser-specific rendering and effects outside the library’s supported property set can differ from what the user sees. Test the styles that matter to your design rather than assuming visual identity.

Cross-origin images

Browser security rules still apply. A remote image must provide suitable CORS headers for useCORS: true to help. If it does not, the image may be skipped or the canvas may become unreadable (“tainted”), preventing export. The alternative documented by html2canvas is a proxy that fetches the image server-side and serves it with permission. You cannot use html2canvas options to bypass another server’s policy.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Images in iframes

Same-origin iframe documents can be recursively rendered. A cross-origin iframe cannot be read because the browser withholds its contentDocument; a sandboxed iframe without allow-same-origin has the same practical restriction. Capture the iframe’s content from the page that owns it, or use a server-side browser where you control navigation and permissions.

Canvas size limits

Very large dimensions can render blank or only partially. The html2canvas FAQ gives rough, platform-dependent guides rather than guarantees: Chrome/Chromium is around 32,767 pixels on one dimension and about 268 megapixels total area; Firefox is around 32,767 pixels and about 472 megapixels; desktop Safari is around 32,767 pixels. iOS Safari limits are lower and depend on device memory. Keep scale and dimensions modest, split long pages into sections, and test on the devices you support.

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

Client-side versus server-side screenshots

html2canvas depends on browser APIs such as window, document and computed styles, so it is client-side code. It will not run directly in a Node.js process without a browser environment. For server-side, full-page screenshots, the html2canvas FAQ points to browser automation such as Puppeteer or Playwright. Browser extensions should generally use their native tab-capture APIs instead of trying to inject html2canvas.

Performance and reliability checklist

  • Capture only the target node instead of the entire document.
  • Use the lowest scale that meets your output requirement.
  • Wait for fonts, images and data before starting the render.
  • Hide videos, animated widgets and controls that are not part of the exported design.
  • Keep oversized scroll regions within tested canvas dimensions; split them when necessary.
  • Handle rejected Promises and show the user a recoverable error.
  • Test Chrome, Firefox, Safari and mobile Safari if the image is part of a customer-facing workflow.

Troubleshooting common failures

“html2canvas is not defined”

The library script has not loaded, loaded after your application code, or is blocked by a content-security policy. Check the Network panel, load the script before the capture code, and verify the global is available before the button handler runs.

“Cannot read properties of null”

querySelector() returned no element. Confirm the ID or class, run the code after the DOM exists, and guard against a missing node before calling html2canvas.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

The image is blank or cropped

Inspect the element’s computed size and overflow. A hidden node, an incorrect viewport, a scroll container or an oversized canvas can all cause this symptom. Try explicit width/height, matching windowWidth/windowHeight, a lower scale, or a split capture.

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

Remote pictures are missing

Open the image URL and check its response headers. If the server does not grant CORS access, useCORS: true cannot fix it; configure the image host or use a permitted proxy.

Text or CSS looks different

Confirm that fonts finished loading and identify unsupported or browser-specific CSS. Simplify the capture styles or provide a capture-only stylesheet. Remember that the result is a DOM/CSS reconstruction, not a compositor screenshot.

Export throws a security error

A cross-origin resource likely tainted the canvas. Remove that resource, make it CORS-enabled, or load it through an authorized proxy before exporting.

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

Or skip the browser setup

If you need a clean screenshot from a URL rather than a canvas embedded in the current page, ScreenshotNeo provides a single GET request. It accepts cookie and consent banners as a visitor, then removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page result and billing status in X-Page-Verdict and X-Billed headers.

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

See the ScreenshotNeo API documentation for all options, including element selectors, full-page lazy-image loading, device presets, retina scale, PDF output, custom JavaScript and CSS, waits, request blocking, cookies, headers, geolocation, caching, signed links, asynchronous jobs, bulk capture and usage reporting.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
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 data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));

ScreenshotNeo also has an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can html2canvas capture an element selected by CSS selector directly?

No. Resolve the selector with document.querySelector() (or another DOM method) and pass the resulting element object to html2canvas().

Does html2canvas create a JPEG as well as a PNG?

The documented download example uses canvas.toDataURL('image/png'). Other canvas export formats depend on the browser’s canvas implementation and your chosen MIME type.

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

Will capturing a div include content below its visible scroll area?

Only when the rendered dimensions include that content. Measure the full scroll region and provide suitable dimensions; otherwise capture separate sections.

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
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.