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

To capture an HTML element after a user action, attach a normal JavaScript event listener, pass the selected element to html2canvas(), await the returned Promise, and export the resulting canvas. The basic flow is:

  1. Choose the element when the event fires.
  2. Run await html2canvas(element).
  3. Convert the canvas to PNG (or another supported format).
  4. Download or display the result.

This is a DOM reconstruction, not a compositor-level browser screenshot. html2canvas rebuilds an image from the DOM and styles it can read, so visual differences are possible.

What “screenshot events” mean in JavaScript

html2canvas does not provide a special screenshot-event system. Your application supplies the trigger—usually a button click, form submission, pointer event, or keyboard shortcut—and html2canvas performs the asynchronous capture. This separation lets you decide exactly when a capture occurs and which element is included.

Complete click-to-download example

Install html2canvas according to its current project instructions. In a package-managed application, that normally means adding the package with your package manager and importing it into the module that handles the event. The code below assumes the library is available as 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.
#1 Best Overall
Sale
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 4x optical zoom with a 27mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen with 2 AA alkaline batteries for convenient on-the-go use
<button id="save-shot" type="button">Download card</button>
<section id="invoice-card">
  <h1>Invoice #1042</h1>
  <p>Total: $128.00</p>
</section>

<script type="module">
  import html2canvas from 'html2canvas';

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

  button.addEventListener('click', async () => {
    button.disabled = true;
    try {
      const canvas = await html2canvas(target);
      const link = document.createElement('a');
      link.href = canvas.toDataURL('image/png');
      link.download = 'invoice-1042.png';
      link.click();
    } catch (error) {
      console.error('Could not create image:', error);
      alert('The image could not be created. Check the console for details.');
    } finally {
      button.disabled = false;
    }
  });
</script>

html2canvas(target) resolves to a canvas. The documented PNG route is canvas.toDataURL('image/png'), assigned to a temporary download link. Keep the try/finally structure in production so a failed capture does not leave the button permanently disabled.

Using a CDN or a global build

If your page loads a browser build that exposes html2canvas globally, remove the import and keep the event handler. Confirm the current distribution instructions before deploying; package names and loading methods can change.

Capture after other events

Form submission

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const canvas = await html2canvas(document.querySelector('#receipt'));
  const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
  if (!blob) throw new Error('Canvas encoding failed');
  // Send blob with fetch(), or create a download URL.
});

Keyboard shortcut

window.addEventListener('keydown', async (event) => {
  if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
    event.preventDefault();
    const canvas = await html2canvas(document.querySelector('#workspace'));
    const link = document.createElement('a');
    link.download = 'workspace.png';
    link.href = canvas.toDataURL('image/png');
    link.click();
  }
});

For long-running captures, prevent overlapping operations. A simple “busy” flag or disabled control avoids two handlers consuming memory simultaneously.

Control what gets captured

Exclude controls and temporary UI

Add data-html2canvas-ignore to any element that should not appear:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<button data-html2canvas-ignore>Download</button>

This is useful for close buttons, editing handles, selection outlines, and status labels.

Capture a region

Pass crop options when you need a rectangle rather than the whole element:

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

The coordinates are interpreted against the rendered target according to html2canvas’s option behavior. Verify the crop visually, especially when the page is scrolled or the target has transforms.

Rank #2
Sale
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 5x optical zoom with a 28mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen and a rechargeable lithium-ion battery for on-the-go use

Increase output density

const canvas = await html2canvas(target, {
  scale: window.devicePixelRatio
});

A larger scale produces more pixels, but it can increase memory use and processing time. For very large or tall elements, choose a deliberate scale instead of blindly using a high-DPI value.

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

Convert the canvas to other outputs

PNG data URL

const pngDataUrl = canvas.toDataURL('image/png');

JPEG with quality

const jpegDataUrl = canvas.toDataURL('image/jpeg', 0.85);

JPEG is smaller for photographic content but does not preserve transparency. PNG is usually better for text, interfaces, and transparent backgrounds.

Blob upload

canvas.toBlob(async (blob) => {
  if (!blob) return;
  const body = new FormData();
  body.append('image', blob, 'capture.png');
  await fetch('/uploads', { method: 'POST', body });
}, 'image/png');

Blob uploads avoid putting a potentially large base64 string in memory and are preferable when sending the image to a server.

How accurate is html2canvas?

The project documentation warns that its result “may not be 100% accurate to the real representation” because it does not make an actual screenshot; it builds one from information available in the page. Unsupported or partially supported CSS can therefore differ from what the browser compositor displayed. Test the exact layouts, fonts, filters, pseudo-elements, and transforms your application uses instead of promising pixel-perfect output.

Cross-origin images, canvases, and iframes

Browser security governs every resource drawn into a canvas. Images hosted on another origin need suitable CORS response headers and an html2canvas configuration that permits the request, or they may taint the canvas. A tainted canvas can prevent toDataURL() and other readback operations.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Prefer same-origin assets when possible.
  • Configure the image host to send an appropriate Access-Control-Allow-Origin header.
  • Use a server-side proxy when you control neither origin nor headers, subject to that site’s terms.
  • Do not expect a browser workaround for a resource that forbids cross-origin reading.

Same-origin iframes can be traversed recursively according to the project documentation. Cross-origin frames cannot be read because scripts cannot access their document. If an embedded payment, video, or analytics frame is cross-origin, capture the surrounding page but not the frame’s private pixels.

Browser support and rendering prerequisites

The project lists modern evergreen browsers, including current Firefox, Chrome/Chromium-based browsers, and Safari. Confirm the supported set for the release you install. Capture only after the target has rendered its final state: wait for data-bound text, images, web fonts, and animations to settle. For deterministic output, temporarily pause animations or add an application-level “ready” state before enabling the capture control.

Rank #3
Sale
Digital Camera, Latest FHD 1080P Digital Camera for Teens with SD Card Anti Shake Point and Shoot Cameras Portable 16X Zoom Compact Small Cameras for Kids Boys Girls Seniors with Wrist Strap
  • Latest Digital Camera Built-in Fill Light : This compact digital camera is paired with a powerful CMOS processor and image stabilization to help you take & record the most exciting moments in 44 MP quality images & FHD 1080P quality videos anywhere, anytime. Plus, there is also a built-in fill light to help you take high quality pictures even in low light&dark settings, making this the perfect camera for all indoors/outdoors situations.
  • Long-Lasting Battery Life & 16X Digital Zoom :This point and shoot camera will retain its battery charge even after long use. The controls and functions are easy to operate making this the perfect choice for children, teens and younger. This kids camera supports 16x digital zoom, you can zoom in or out the subject by pressing the W/T button for taking still photos to zoom in or out on distant objects and capture all the details you need.
  • Multifunctional & Portable Digital Camera: This cheap digital camera is slim enough to fit in your pocket. You'll easily be able to take it with you on all your indoor/outdoor activities and adventures and ideal for beginners, children and teenagers. This kids digital camera is equipped with 20 filters, anti-shaking, self-timer, continuous shooting, date stamp, time-lapse recording, smile capture, internal MIC and speaker (recording sound videos), great for your daily photography needs.
  • WEBCAM & PAUSE FUNCTION : More than just a FHD 1080p digital camera, it also works as a webcam for video calls and vlogging. Connect the camera to the computer, press shutter and power button at the same time and the camera will automatically turn on webcam mode for all your video calling and live streaming needs. The pause function allows you to pause when seeing playback videos.
  • A Must Have Photography Device : This digital camera with SD card made from high-quality materials, this retro camera is safe and durable. Perfect for all ages to develop & improve their photographic abilities and observation skills. Our dedicated and experienced 24/7 support team is available for all after purchase troubleshooting, questions and technical help.

Common failures and fixes

The result is blank or incomplete

  • Cause: capture started before content finished rendering. Fix: trigger after your data/render promise resolves and verify images have loaded.
  • Cause: an element is outside the intended visible state or is hidden by CSS. Fix: inspect computed styles and capture the visible ancestor.

SecurityError when exporting

A cross-origin image or canvas probably tainted the result. Move the asset same-origin, configure CORS, or proxy it from a server you control.

Text or CSS looks different

DOM reconstruction supports only the CSS properties the library understands. Simplify unsupported effects, wait for web fonts, and compare at the same viewport and device scale.

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

An iframe is missing

Only same-origin iframe documents are readable. Render essential content in the parent document or provide a server-side capture path for content you are authorized to process.

The browser becomes slow or crashes

Large dimensions and high scale values allocate large bitmaps. Capture a smaller region, lower the scale, remove unnecessary content, and release references after download or upload.

Client-side capture or a hosted screenshot API?

Use html2canvas when the source is a live DOM element, the user is already in the browser, and browser security boundaries are acceptable. A hosted renderer is more suitable when the input is a publicly reachable URL or rendering must happen outside the user’s browser. Evaluate where scripts execute, whether you can supply custom scripts, cross-origin behavior, control of the rendering environment, API-key requirements, and dependence on an external service.

ScreenshotNeo is the hosted option to try first: it removes consent banners, newsletter popups, and chat widgets before capture; only clean shots are billed; and its paid plan starts at $5 for 3,000 shots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 loads a URL and returns a PNG, JPEG, WebP, or PDF. It also offers selector waits, delays, network-idle waits, full-page lazy-image loading, CSS-selector element capture, custom JavaScript, cookies and headers, device presets, dark mode, PDF controls, blocking rules, caching, signed links, asynchronous jobs, bulk capture, and an MCP server for AI clients. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

See the ScreenshotNeo documentation for all parameters. A one-call capture looks like this:

Rank #4
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
  • 16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting
  • Optical Zoom: 5x optical zoom with a 28mm wide angle lens for flexible framing indoors or outdoors
  • Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
  • Memory Support: Works with Class 10 SD, SDHC, or SDXC cards up to 512GB
  • LCD Screen and Battery: 2.7in LCD screen and a rechargeable lithium-ion battery for on-the-go use
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}`);

The free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Pricing and operational choices

ScreenshotNeo’s listed plans are:

Plan Price Included shots
Free $0 1,000/month
Starter $5 3,000
Growth $15 15,000
Pro $39 60,000
Scale $99 250,000
Business $249 1,000,000

Yearly billing gives two months free, and every feature is available on every plan. Client-side html2canvas has no API charge, but your users’ devices, browser security, and rendering consistency remain part of the system you operate.

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

Frequently Asked Questions

Can html2canvas capture the browser’s exact pixels?

No. It reconstructs an image from DOM and style information, so unsupported CSS and browser-compositor details can differ.

Can I capture a cross-origin iframe?

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

Should I use PNG or JPEG?

Use PNG for interfaces, text, and transparency; use JPEG when photographic content and a smaller lossy file are more important.

Do I need a server for html2canvas?

Not for a local, same-origin DOM capture. You may need a server for CORS proxying, protected content, or hosted URL rendering.

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

Quick Recap

SaleBestseller No. 1
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
Kodak PIXPRO FZ45 Digital Camera, 16MP Point & Shoot (Black)
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$99.99
SaleBestseller No. 2
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
Kodak PIXPRO FZ55-BK 16MP CMOS Sensor Camera 5X Optical Zoom 28mm Wide
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$139.99
Bestseller No. 4
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
Kodak PIXPRO FZ55-RD 16MP Camera 5X Optical Zoom 28mm Wide Angle 1080p
16MP Sensor: Captures detailed photos with a CMOS sensor for everyday shooting; Full HD Video: Records 1080p video for travel clips, family moments, or simple vlogging
$139.99

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.