DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
DOM

How to Capture a Screenshot of a Specific DOM Element with Vanilla JavaScript

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

Use a DOM-to-canvas renderer, not the native Canvas API. For an arbitrary <div>, card, chart, or other HTML element, load html2canvas, pass the element to html2canvas(element), then export the returned canvas with toBlob(). The example below captures one element, waits for it to render, preserves device-pixel sharpness, and downloads a PNG without navigating away.

Complete vanilla JavaScript example

This is “vanilla JavaScript” at the application-code level: there is no framework, build step, or wrapper library. html2canvas is still required because browsers do not expose a general API that converts live HTML and CSS into pixels.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Element screenshot</title>
  <script src="https://cdn.jsdelivr.net/npm/html2canvas@latest/dist/html2canvas.min.js"></script>
  <style>
    #capture { width: 420px; padding: 24px; background: white; color: #111; border: 1px solid #ddd; }
  </style>
</head>
<body>
  <section id="capture">
    <h1>A card to capture</h1>
    <p>Only this section becomes the image.</p>
    <button data-html2canvas-ignore>Do not include me</button>
  </section>
  <button id="save" type="button">Download PNG</button>

  <script>
    document.querySelector('#save').addEventListener('click', async () => {
      const element = document.querySelector('#capture');
      if (!element) throw new Error('Target element was not found');

      // Let web fonts and images finish before rendering.
      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 canvas = await html2canvas(element, {
        scale: window.devicePixelRatio,
        useCORS: true
      });

      const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
      if (!blob) throw new Error('Canvas export failed');
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'capture.png';
      link.click();
      URL.revokeObjectURL(url);
    });
  </script>
</body>
</html>

Save this as an HTML file and serve it from a local web server rather than opening it with a file:// URL. Click Download PNG; the section with id="capture" is rendered and downloaded. The data-html2canvas-ignore attribute excludes a node from the result.

Why native Canvas cannot screenshot a normal div

The native CanvasRenderingContext2D API draws pixels from sources such as an image, another canvas, an ImageBitmap, or video. Its drawImage() method can crop and scale those sources, but it does not interpret the browser’s layout tree, computed CSS, pseudo-elements, or fonts. A live div must first be reconstructed by a DOM renderer such as html2canvas.

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

Use native canvas directly when the source is already an image or canvas. For example, this crops an existing image into a new file:

const source = document.querySelector('#source-image');
const crop = document.createElement('canvas');
crop.width = 400;
crop.height = 300;
crop.getContext('2d').drawImage(source, 20, 20, 400, 300, 0, 0, 400, 300);
crop.toBlob(blob => {
  if (!blob) return;
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = 'crop.png';
  link.click();
}, 'image/png');

Do not confuse this image-cropping route with capturing HTML. It will not reproduce a styled card, table, or form unless those pixels already exist in an image or canvas.

Capture a selected element by CSS selector

Wrap the operation in a reusable function so any selector can be captured. Validate the selector result and return a real Blob, which is safer for large downloads than a giant data URL.

async function elementToPng(selector, filename = 'element.png') {
  const element = document.querySelector(selector);
  if (!element) throw new Error(`No element matches ${selector}`);

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

  const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
  if (!blob) throw new Error('PNG encoding failed');

  const href = URL.createObjectURL(blob);
  const anchor = Object.assign(document.createElement('a'), {
    href,
    download: filename
  });
  anchor.click();
  setTimeout(() => URL.revokeObjectURL(href), 0);
}

document.querySelector('#save').onclick = () => elementToPng('.invoice-card', 'invoice.png');

Geometry, scrolling and precise regions

element.getBoundingClientRect() returns the smallest rectangle containing the element, including padding and border. Its left, top, right, and bottom coordinates are relative to the viewport, so they change when the page scrolls. Add window.scrollX and window.scrollY to convert the top-left point to document coordinates.

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
const box = element.getBoundingClientRect();
const documentX = box.left + window.scrollX;
const documentY = box.top + window.scrollY;
console.log({ x: documentX, y: documentY, width: box.width, height: box.height });

For an element that is split across lines, such as an inline link, getClientRects() can return several rectangles. Decide whether your UI should capture the union of those rectangles or one particular fragment. Most block-level cards and panels need only getBoundingClientRect().

html2canvas can render a specific region with x, y, width, and height. Those options are useful when you need a crop around a larger rendered area, but passing the target element is usually simpler and preserves its natural box.

Sharp output and export formats

Device-pixel ratio

Set scale: window.devicePixelRatio for high-density displays. A 420 CSS-pixel-wide card on a device with a ratio of 2 becomes roughly 840 physical pixels wide, producing a sharper image. Very high ratios increase memory use; cap the value for large or numerous captures if the page becomes slow.

PNG, JPEG and WebP

PNG is the safest default for text, transparency and UI screenshots. You can request JPEG or WebP when supported:

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.
const blob = await new Promise(resolve =>
  canvas.toBlob(resolve, 'image/jpeg', 0.88)
);

The quality argument applies to lossy formats. If the requested format is missing or unsupported, browsers use PNG. Prefer toBlob() and an object URL for downloads. toDataURL() creates a base64 string in memory and can produce very large values that are awkward to store or place in a URL.

Images, fonts, iframes and CSS limitations

Cross-origin images

useCORS: true asks the renderer to load remote images with CORS. The image server must also send an appropriate Access-Control-Allow-Origin header. Without that permission, the image may be omitted or the canvas may become non-origin-clean; exporting it can then throw a SecurityError.

For assets you control, serve them from the same origin or configure CORS. A proxy is another option, but it must be designed carefully so it cannot be abused as an open request relay.

Fonts and loading state

Capture only after the visual state is complete. Await document.fonts.ready where available and wait for images, as in the complete example. If a web font is still downloading, the screenshot can contain fallback glyphs even though the page later looks correct.

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

Iframes and unsupported CSS

html2canvas rebuilds a screenshot from DOM information; it does not take a literal browser screenshot. CSS properties that the renderer does not understand may differ from the live page. Cross-origin iframes cannot be read because their contentDocument is inaccessible. Same-origin iframes can be processed recursively. Complex filters, plugins, video overlays and browser UI are therefore not guaranteed to match.

Hide controls and prepare a capture-only view

Add data-html2canvas-ignore to buttons, toolbars, hover hints or other nodes that should not appear. For larger changes, temporarily add a class before rendering and remove it in a finally block:

async function captureWithoutToolbar() {
  const target = document.querySelector('#report');
  target.classList.add('capture-mode');
  try {
    return await html2canvas(target, { scale: window.devicePixelRatio });
  } finally {
    target.classList.remove('capture-mode');
  }
}

Keep the target’s dimensions stable while capturing. Animations, carousels, blinking cursors and lazy-loaded content can otherwise produce inconsistent frames. Pause them with a capture-only class or wait for the desired state.

Common failures and fixes

Symptom Likely cause Fix
html2canvas is not defined The script did not load, or the click happened first. Check the browser network panel, keep the script before your code, and wait for page load.
Target is null The selector is wrong or the script runs before the element exists. Use the exact ID/class and run after the DOM is parsed.
Remote images are missing The image server disallows CORS. Host the asset on the same origin or configure CORS; useCORS cannot override server policy.
SecurityError during export A cross-origin resource tainted the canvas. Remove that resource, fix its CORS headers, or use a permitted proxy.
Text looks soft Output scale is one CSS pixel per image pixel. Use scale: window.devicePixelRatio, while monitoring memory.
Blank or incomplete capture Fonts, images, lazy content or animations are still loading. Await fonts and images, trigger lazy loading, pause motion, then capture.
Layout differs from the page Unsupported CSS, cross-origin iframe, or a state that changed during rendering. Simplify capture CSS, use same-origin frames, and freeze the visual state.
Browser freezes on large pages High-resolution canvases consume substantial memory. Capture only the element, reduce scale, avoid data URLs, and release object URLs.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability and security considerations

  • Capture the smallest useful node. Rendering the whole document costs more than rendering one card.
  • Control pixel dimensions. Element width × height × scale² approximates the pixel workload; multiplying scale from 1 to 2 can require about four times as many pixels.
  • Release resources. Revoke object URLs after the download and do not retain canvases or blobs unnecessarily.
  • Do not treat a client-side image as trusted evidence. Users can alter the DOM before capture. For audit-grade records, render from a controlled server or store the original data as well.
  • Protect sensitive content. The resulting image contains whatever the target displays. Avoid logging data URLs or uploading blobs without an explicit privacy policy.

Or skip the browser setup

If you need a server-side screenshot rather than a browser-generated reconstruction, ScreenshotNeo returns a PNG, JPEG, WebP or PDF from one request. It accepts consent banners before capture 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 the response identifies the result with X-Page-Verdict and X-Billed headers.

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

For a page-level capture, call the API with your access key and target URL. The complete option list and parameter reference are in the ScreenshotNeo documentation.

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(`HTTP ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', bytes);

ScreenshotNeo also provides element capture by CSS selector, full-page lazy-image loading, custom CSS and JavaScript, click-before-capture actions, waits for selectors or network idle, device presets and viewports, retina scale, headers, cookies, user agents, authorization, geolocation, timezone, request blocking, resizing, caching with a chosen TTL, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, OpenAPI, PDF controls and 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 each month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan. Create a free ScreenshotNeo account.

FAQ

Can I capture an element without any library?

Not as a general HTML-to-pixels operation. Native canvas can crop existing image or canvas sources, but arbitrary DOM and CSS require a renderer such as html2canvas or a browser automation service.

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

Does html2canvas create a pixel-perfect browser screenshot?

No. It reconstructs the image from DOM information, so unsupported CSS, cross-origin frames and some browser-rendered effects can differ from the live page.

Should I use toDataURL() for downloads?

Use toBlob() with an object URL for normal and large captures. Data URLs duplicate image data in a string and can become unwieldy.

Why does an inline element produce several boxes?

Inline content can wrap across lines. getClientRects() exposes each fragment; choose whether your UI needs one fragment or a union of them.

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 *

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.

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.