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 DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
html2canvas

How to Capture an HTML Element Screenshot With JavaScript

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.

To capture one element in a web page with JavaScript, use html2canvas for an in-page export button, or use Playwright’s locator.screenshot() when you need a real browser screenshot in an automated process. The choice matters: html2canvas reconstructs an image from the DOM and can differ from the browser’s rendered pixels; Playwright captures the element from a controlled browser.

Choose the right capture method

Need Use Why
A user clicks a button to export a card or report inside the current page html2canvas Runs in the page and returns a canvas you can download or process.
Automated screenshots, visual tests, or output that should reflect browser rendering Playwright Controls a browser and supports screenshots of a locator, page, or full page.
A screenshot of a public URL without setting up browser automation ScreenshotNeo A screenshot API and MCP server; its capture options include selecting an element by CSS selector.

Capture and download an element with html2canvas

Install the package

For a project using npm, install the package with:

npm install @html2canvas/html2canvas

Then import it into your JavaScript module. The documented API is Promise-based: call html2canvas(element, options) and await the resulting canvas. See the html2canvas documentation.

Render a selected element

Give the target a stable selector, then check that it exists before calling the library:

import html2canvas from '@html2canvas/html2canvas';

const element = document.querySelector('#capture');
if (!element) throw new Error('Element not found');

const canvas = await html2canvas(element, {
  backgroundColor: '#ffffff',
  scale: window.devicePixelRatio,
  useCORS: true
});

document.body.appendChild(canvas);

This example uses a white background, scales the output to the device pixel ratio, and requests CORS-enabled image loading. useCORS: true does not bypass the remote image server’s permissions; the server must allow the image to be used cross-origin.

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

Download the result as PNG

For a small result, a PNG data URL and temporary anchor are straightforward:

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

For a larger canvas, use a Blob rather than creating a long base64 data URL:

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

Both methods are documented in the html2canvas examples. If you need to retain or upload the Blob, do that before revoking its object URL; this example revokes immediately after triggering the download.

Control the captured area and image quality

Capture just the element or crop coordinates

Passing the target element directly to html2canvas is generally simpler than capturing the page and cropping it. If you capture a larger root, the x, y, width, and height options can restrict the rendered region; use coordinates and dimensions that match the intended region.

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.
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

Choose output scale deliberately

The default output may be smaller than expected on a high-density display. Setting scale: window.devicePixelRatio creates a device-pixel-sized result, which can look sharper when displayed or printed at the corresponding size. It also increases pixel count and memory use: doubling scale in each dimension yields roughly four times as many pixels. Use a smaller fixed scale if memory or download size matters more than Retina-level detail.

Omit controls and private interface elements

Add data-html2canvas-ignore to nodes that should not be included, such as an export button or a private control:

<div id="capture">
  <h2>Report</h2>
  <button data-html2canvas-ignore>Delete</button>
</div>

The ignore attribute is described in the html2canvas examples.

Wait for content before capturing

Starting capture immediately after inserting an element can produce an image without its final fonts, images, or application data. Wait for the conditions your page actually depends on. For example, this helper waits for document fonts and image elements inside the target to finish loading or fail:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy 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.
async function waitForElementAssets(element) {
  if (document.fonts?.ready) await document.fonts.ready;

  const images = [...element.querySelectorAll('img')];
  await Promise.all(images.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 element = document.querySelector('#capture');
if (!element) throw new Error('Element not found');
await waitForElementAssets(element);
const canvas = await html2canvas(element, { useCORS: true });

This is an implementation precaution, not a promise that the library can know when your application’s asynchronous data is ready. If the element depends on a fetch request, chart animation, or framework state update, wait for that condition explicitly before calling the helper.

Understand html2canvas fidelity and browser security

html2canvas does not copy the final pixels produced by the browser compositor. It traverses the DOM and draws what it can interpret into a canvas, so some CSS or visual effects may be missing or different. The project states that “The screenshot is based on the DOM and as such may not be 100% accurate to the real representation” in its documentation. If matching the browser’s actual rendering is essential, use Playwright instead.

  • Cross-origin images: images generally must be same-origin or served with appropriate CORS headers. useCORS: true requests CORS use but cannot grant permission the image server has not provided.
  • Cross-origin iframes: browser security prevents access to another origin’s contentDocument, so html2canvas cannot render that frame’s contents.
  • Tainted canvas: drawing a cross-origin image without the required permission can taint the canvas. Reading or exporting it may then fail, including calls such as toDataURL().

These constraints are described in the html2canvas documentation and examples.

Capture an element with Playwright

Playwright is appropriate when your code controls a browser process—for example, a visual regression test, a scheduled capture, or a Node.js job. Install Playwright and its browser using the setup instructions for your project, then use the locator screenshot API:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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
import { chromium } from 'playwright';

const browser = await chromium.launch();
try {
  const page = await browser.newPage({ deviceScaleFactor: 1 });
  await page.goto('https://example.com');
  await page.locator('.header').screenshot({ path: 'header.png' });
} finally {
  await browser.close();
}

The example opens a page, takes a screenshot of the first matching .header locator, writes header.png, and closes the browser even if capture fails. Consult the Playwright screenshots guide for locator, page, and full-page examples.

Keep the screenshot in memory

Omit path to receive PNG bytes as a buffer, which you can pass to storage or an image-diff function:

const pngBytes = await page.locator('.header').screenshot();
// Send pngBytes to storage, an image diff, or another service.

The Page API documents this buffer-returning behavior and screenshot options at Playwright Page API. The screenshot options documentation covers element targets, PNG/JPEG/WebP output, full-page capture, and CSS versus device scaling: Playwright screenshot options.

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 the input is a URL and you want the capture handled remotely, ScreenshotNeo can return a PNG, JPEG, WebP, or PDF from one GET request. Its element-capture option lets you target a CSS selector. For example, this cURL call captures a page URL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

See the ScreenshotNeo API documentation for authentication and capture parameters, including element selection. Its clean-shot options can accept cookie or consent banners and remove 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 responses report the page verdict and billing status in headers. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for AI agents and other MCP clients.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is available on every plan. Sign up for 1,000 free screenshots a month with no card.

Troubleshooting common capture failures

  • “Element not found” or a null target: run capture after the DOM contains the target and verify the selector, including whether the code runs before the page has mounted.
  • Images are missing: wait for image load, then confirm remote servers return suitable CORS headers. Enabling useCORS alone cannot fix a server that disallows cross-origin use.
  • Export throws a security error: one or more drawn images may have tainted the canvas. Serve them same-origin or configure the image host for CORS; an inaccessible cross-origin iframe cannot be worked around by reading its document.
  • Fonts or asynchronous UI look unfinished: wait for document.fonts.ready and the page’s own data or rendering signals before capture.
  • Styles differ from the visible browser page: this may be a reconstruction limitation of html2canvas rather than a selector bug. Reproduce the capture with Playwright if rendered-browser fidelity is required.
  • Large output is slow or consumes too much memory: capture the element rather than the whole document, lower scale, and prefer Blob output over a large data URL.
  • Playwright cannot capture a locator: confirm the browser launch and navigation completed and that the locator matches an element on the loaded page. Use a more specific locator where the page has repeated matches.

FAQ

Can JavaScript screenshot a div without a server?

Yes. html2canvas runs in the page and can render a selected element to a canvas. Cross-origin image permissions and CSS support still constrain the result.

Can html2canvas capture a cross-origin iframe?

No. Browser same-origin security blocks access to a cross-origin iframe’s document.

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

Which method should I use for a visual regression test?

Use Playwright when the test should capture browser-rendered output under a controlled browser setup.

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