October 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 PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
html2canvas

How to Capture a Client-Side Screenshot with JavaScript

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

Choose the capture method that matches what you need: use html2canvas to render an element your page can access, or the browser’s Screen Capture API to let a user choose a tab, window, or screen. They are not interchangeable. html2canvas reconstructs an image from readable DOM information; getDisplayMedia() returns a video stream of a user-selected display surface.

Choose the right kind of screenshot

What you need Starting point Main trade-off
An element or region in your app html2canvas It rebuilds the view from DOM data and supported styles, so it may differ from the browser’s actual rendered pixels. Cross-origin assets and frames are constrained.
A tab, window, or monitor selected by the user navigator.mediaDevices.getDisplayMedia() The browser opens a picker and requires user activation and permission. The API gives you a stream, not a still image.
A browser-extension capture Browser extension screenshot APIs The html2canvas FAQ points extension authors to native extension APIs, which avoid html2canvas’s canvas-size limits.
A screenshot generated on a server Puppeteer or Playwright These automate a headless browser; they are not client-side capture.

The html2canvas project describes its output as based on DOM information rather than an actual screenshot of the page. Use it when a reconstructed image of an app-owned element is sufficient. If the requirement is to capture what the user sees in a chosen browser surface, use display capture instead.

Capture an HTML element with html2canvas

Install html2canvas in your JavaScript project with npm install html2canvas. The example below captures an element with the ID receipt, converts the canvas to a PNG blob, and downloads it. It assumes your app has a button with the ID save-shot and an element with the ID receipt.

import html2canvas from 'html2canvas';

const button = document.querySelector('#save-shot');
const target = document.querySelector('#receipt');

button.addEventListener('click', async () => {
  if (!target) {
    console.error('Screenshot target #receipt was not found.');
    return;
  }

  button.disabled = true;
  try {
    const canvas = await html2canvas(target, {
      backgroundColor: '#ffffff',
      scale: window.devicePixelRatio || 1
    });

    if (canvas.width === 0 || canvas.height === 0) {
      throw new Error('Capture produced an empty canvas.');
    }

    canvas.toBlob((blob) => {
      if (!blob) {
        console.error('The browser could not encode the canvas as PNG.');
        return;
      }
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'receipt.png';
      link.click();
      URL.revokeObjectURL(link.href);
    }, 'image/png');
  } catch (error) {
    console.error('Screenshot failed:', error);
  } finally {
    button.disabled = false;
  }
});

Call the library with the specific element, not document.body, unless the whole rendered document is really what you need. Smaller targets use less memory and are easier to inspect. The resulting canvas is an image reconstruction; complex layout, unsupported CSS, or content the page cannot read may be missing or rendered differently.

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

Remote images, canvases, and iframes

For a remote image to appear in a capture, it generally needs to be same-origin, served with CORS permission, or fetched through a suitable proxy. A browser may display an image that JavaScript is not allowed to read back. Existing canvases that have been tainted by cross-origin content can also prevent safe readback or export.

A page cannot traverse the DOM inside a cross-origin iframe because its contentDocument is unavailable to the parent page. If that frame is essential, capture a user-selected browser surface instead, or use an authorized server-side or extension-based approach. Do not assume that setting an option on the renderer overrides browser origin security.

Large and full-page captures

Large outputs consume substantial memory, especially at high device-pixel scale. Browser and platform canvas limits vary; oversized canvases can be blank or partial without an exception. Check the output dimensions and inspect the actual downloaded image on the browsers and devices you support. If a long page is unreliable, capture smaller sections or use a browser extension or headless-browser workflow suited to the job.

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

Capture a user-selected tab, window, or screen

getDisplayMedia() is the browser-native route when the user must choose what to share. It requires a secure context in supporting browsers, a transient user gesture, and the user’s permission. The browser’s picker determines the selectable surface; the calling page cannot silently choose a particular tab or monitor. The result is a MediaStream, generally with a video track and possibly audio. To save a still, draw a frame from the stream’s video track onto a canvas.

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

This example wires capture to a button click, shows a preview, and saves a PNG after the user chooses a source. Include a video element with ID preview and a button with ID capture-display.

const captureButton = document.querySelector('#capture-display');
const preview = document.querySelector('#preview');

captureButton.addEventListener('click', async () => {
  if (!navigator.mediaDevices?.getDisplayMedia) {
    console.error('Display capture is not available in this browser or context.');
    return;
  }

  let stream;
  try {
    // Keep this call directly in the user-activated click handler.
    stream = await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: false
    });
    preview.srcObject = stream;
    await preview.play();

    const track = stream.getVideoTracks()[0];
    if (!track) throw new Error('No video track was returned.');

    const settings = track.getSettings();
    const canvas = document.createElement('canvas');
    canvas.width = settings.width || preview.videoWidth;
    canvas.height = settings.height || preview.videoHeight;
    if (!canvas.width || !canvas.height) {
      throw new Error('The selected surface has no available video dimensions.');
    }

    canvas.getContext('2d').drawImage(preview, 0, 0, canvas.width, canvas.height);
    canvas.toBlob((blob) => {
      if (!blob) {
        console.error('The browser could not encode the frame.');
        return;
      }
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'display.png';
      link.click();
      URL.revokeObjectURL(link.href);
    }, 'image/png');
  } catch (error) {
    // Includes user cancellation or denial; avoid treating it as a silent capture.
    console.error('Display capture was not completed:', error);
  } finally {
    stream?.getTracks().forEach((track) => track.stop());
    if (preview) preview.srcObject = null;
  }
});

Because the picker can expose private windows, notifications, or unrelated tabs, explain what the browser will ask the user to select. Show a preview and let the user confirm before uploading or sharing the frame. If this code runs inside an iframe, the embedding page’s Permissions Policy may need to allow display-capture.

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.

Or skip the browser setup

If you need a screenshot returned by an API rather than a browser-local capture, ScreenshotNeo takes a URL and returns an image or PDF. This is a different workflow from capturing a DOM element or asking a user to share their screen.

cURL example (see the ScreenshotNeo API documentation for request options):

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie and consent banners, newsletter popups, and chat widgets are handled before the shot; those steps can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; the response reports the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The Free plan includes 1,000 screenshots per month without a card. Paid plans start at $5 for 3,000 screenshots; yearly billing gives two months free.

Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month with no card.

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
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

  • The html2canvas output differs from the page. It reconstructs from accessible DOM and supported styles, rather than reading the browser’s rendered pixels. Simplify unsupported styling or use display capture when literal on-screen content matters.
  • A remote image is missing or export fails. Check whether the asset is same-origin or its server permits CORS. A canvas previously tainted by cross-origin content may not be readable; a proxy is another option where appropriate.
  • Content inside an iframe is absent. A cross-origin parent page cannot inspect the frame’s document. Capture the selected display surface or use a separate authorized workflow.
  • The display-capture picker does not open. Check for a secure context, supported browser, direct user activation, and applicable iframe Permissions Policy. Handle a denied permission or a user cancelling the picker as an expected outcome.
  • The display capture works but no image is saved. The API returns a stream, not a screenshot file. Wait for a usable video frame, draw it to a nonzero-size canvas, and check that toBlob() returned a blob.
  • A very tall capture is blank or cut off. Canvas dimensions and area limits depend on browser and platform, and failure may not throw. Reduce the capture area or scale and verify output on target devices.

Performance, reliability, and cost considerations

DOM rendering runs in the user’s browser and requires access to the page content, making it practical for an app-owned card, receipt, or chart. It can add CPU and memory pressure for large regions, and output fidelity depends on what the renderer can reconstruct. Display capture depends on the user completing the picker and granting access; it captures a chosen surface rather than an arbitrary hidden page element.

Neither client-side route gives you a silent, universally reliable full-page image of any website. For an extension, use the browser’s extension capture APIs as the html2canvas FAQ recommends. For automated screenshots generated away from a user’s browser, Puppeteer or Playwright are server-side alternatives. A URL-based screenshot API is another distinct option when you want a service to load a page and return an image, rather than capture the current client DOM.

Frequently Asked Questions

Can a webpage take a screenshot without asking the user?

Not of a tab, window, or screen through the Screen Capture API: the user must activate the request, choose a surface, and grant permission. A page can render DOM it can access with a library such as html2canvas, but that is a reconstruction, not a silent capture of arbitrary browser pixels.

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.

Can JavaScript capture content in a cross-origin iframe?

The embedding page cannot inspect a cross-origin frame’s document through the DOM. If the user needs that visible content captured, a selected-surface workflow or another authorized capture architecture is needed.

Does html2canvas make an exact screenshot?

No. It builds an image from DOM information and supported styles, so the result can differ from the browser’s rendered pixels.

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

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.