The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →The right JavaScript method depends on what you need to capture. To render an app-owned element or region, use html2canvas, which reconstructs an image from DOM information. To let a user choose a browser tab, window, or monitor, use the browser-native navigator.mediaDevices.getDisplayMedia() API, then draw a video frame to a canvas. Neither approach silently captures arbitrary pixels: DOM rendering is an approximation, while display capture requires a secure context, a user gesture, permission, and a user-selected surface.
Choose the capture model first
| Requirement | Starting point | Trade-off |
|---|---|---|
| An element or app-owned region | html2canvas | Rebuilds the view from readable DOM and supported styles; it is not a pixel-perfect browser screenshot. |
| A user-selected tab, window, or monitor | getDisplayMedia() |
Shows a browser picker, returns a stream, and requires permission and transient user activation. |
| A browser extension | Extension screenshot APIs | They are generally more suitable for browser pixels and avoid html2canvas canvas-size limitations. |
| Server-generated images | Puppeteer or Playwright | These drive a headless browser and are not client-side capture. |
Compare fidelity, cross-origin content, iframe access, permission experience, browser support, output dimensions, and whether the user must select a display surface. The html2canvas documentation explicitly says its result is based on the DOM rather than an actual screenshot of rendered pixels.
Capture an HTML element with html2canvas
1. Load the library
Install it with your package manager or load the browser bundle. With npm:
npm install html2canvas
import html2canvas from 'html2canvas';
For a simple page, a script tag can load the published browser build:
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
<script src="https://cdn.jsdelivr.net/npm/html2canvas@latest/dist/html2canvas.min.js"></script>
Pin a tested version in production rather than relying on a moving @latest URL.
2. Render the target and download a PNG
const button = document.querySelector('#save-shot');
const target = document.querySelector('#invoice');
button.addEventListener('click', async () => {
if (!target) return;
button.disabled = true;
try {
const canvas = await html2canvas(target, {
backgroundColor: '#ffffff',
scale: window.devicePixelRatio
});
const link = document.createElement('a');
link.download = 'invoice.png';
link.href = canvas.toDataURL('image/png');
link.click();
} catch (error) {
console.error('Screenshot failed', error);
} finally {
button.disabled = false;
}
});
Call html2canvas(element, options) after the content and fonts you need are loaded. The promise resolves to a canvas; use toBlob() for a more memory-efficient upload:
const canvas = await html2canvas(document.querySelector('#report'));
canvas.toBlob(async blob => {
if (!blob) throw new Error('Canvas export failed');
await fetch('/upload', { method: 'POST', body: blob });
}, 'image/png');
Useful options
scalecontrols output density. Device-pixel-ratio scaling produces sharper images but increases memory use.backgroundColorsets a solid background; usenullwhen transparency is required and supported by the rendered content.useCORS: trueallows images that are served with suitable CORS headers.proxycan route remote images through a same-origin proxy when your architecture provides one.ignoreElementsor anonclonecallback can hide controls, add print-only styling, or modify the cloned document before rendering.
What html2canvas cannot guarantee
It walks DOM nodes and paints a representation from information readable by the page. Unsupported CSS, browser rendering differences, filters, plugins, and complex compositing can differ from what the user sees. A cross-origin image without permissive CORS can taint the canvas, making export unreadable. Cross-origin iframe contents cannot be traversed because the page cannot access their contentDocument. Same-origin assets, CORS headers, or a server proxy are required for reliable remote-image capture.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Long pages and canvas limits
Very large captures can become blank or partial without a useful exception. Browser and platform canvas dimensions and total-area limits vary; html2canvas’s FAQ treats its guidance as approximate, not a cross-browser guarantee. Capture sections separately, reduce scale, check canvas.width and canvas.height, and inspect the exported image on every target browser and device.
Capture a tab, window, or screen with getDisplayMedia()
Requirements and user experience
- Serve the page from a secure context (normally HTTPS; localhost is commonly treated as secure for development).
- Call from a click or another transient user activation.
- Let the browser show its picker; the page cannot silently force a particular tab or monitor.
- Handle permission denial, cancellation, unsupported browsers, and a user selecting the wrong surface.
- If running in an iframe, its Permissions Policy may need to allow
display-capture.
Because display capture can expose private information, show a preview and obtain confirmation before uploading or sharing the image.
Complete still-image example
<button id="capture">Choose a surface</button>
<video id="preview" autoplay muted playsinline></video>
<button id="save" disabled>Save frame</button>
<canvas id="frame" hidden></canvas>
<script>
const capture = document.querySelector('#capture');
const preview = document.querySelector('#preview');
const save = document.querySelector('#save');
const canvas = document.querySelector('#frame');
let stream;
capture.addEventListener('click', async () => {
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: false
});
preview.srcObject = stream;
await preview.play();
save.disabled = false;
stream.getVideoTracks()[0].addEventListener('ended', () => {
save.disabled = true;
preview.srcObject = null;
});
} catch (error) {
if (error.name === 'NotAllowedError') {
console.warn('The user denied or cancelled screen sharing.');
} else if (error.name === 'NotSupportedError' || !navigator.mediaDevices) {
console.error('Display capture is unavailable in this browser or context.');
} else {
console.error('Display capture failed', error);
}
}
});
save.addEventListener('click', () => {
const track = stream?.getVideoTracks()[0];
if (!track || preview.readyState < 2) return;
canvas.width = preview.videoWidth;
canvas.height = preview.videoHeight;
canvas.getContext('2d').drawImage(preview, 0, 0);
canvas.toBlob(blob => {
if (!blob) return;
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = 'screen.png';
link.href = url;
link.click();
URL.revokeObjectURL(url);
}, 'image/png');
});
</script>
getDisplayMedia() returns a MediaStream, not a still image. The example displays its video track and draws the selected frame onto a canvas. Stop tracks when finished:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
stream?.getTracks().forEach(track => track.stop());
preview.srcObject = null;
Audio and constraints
You may request audio with audio: true, but availability depends on the selected surface and browser. Video constraints can influence the stream, yet the picker and browser remain in control. Do not treat constraints as a way to bypass user choice.
Common failures and fixes
Blank or incomplete html2canvas output
- Check for cross-origin images and configure CORS or a proxy.
- Remove or replace cross-origin iframes; they cannot be inspected by the parent page.
- Reduce capture size or scale and verify canvas dimensions before export.
- Wait for images, web fonts, and asynchronous data before calling the renderer.
- Use
oncloneto apply capture-specific CSS where a live animation or overlay causes differences.
SecurityError when exporting
A canvas containing a non-CORS image may be tainted. Serve the image with an appropriate Access-Control-Allow-Origin response and set the image’s CORS mode before it loads, or use a trusted same-origin proxy. You cannot repair a canvas after tainting.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsgetDisplayMedia() throws or never opens
- Move the call directly into a user click handler.
- Use HTTPS and verify that an iframe’s Permissions Policy permits display capture.
- Check
navigator.mediaDevicesand browser support. - Handle
NotAllowedErrorfor denial or cancellation and ask the user to select a surface again.
Unexpected private content
Explain exactly what the picker can share, display the captured preview, and let the user discard it before upload. Never assume the selected tab is the intended one.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Performance, reliability, and security practices
- Capture only the required element instead of the entire document.
- Use a lower scale for previews and a higher scale only for final exports.
- Release object URLs, stop media tracks, and avoid retaining large canvases.
- Test responsive layouts, fonts, lazy-loaded images, dark mode, and high-DPI devices.
- Apply upload limits and authentication; screenshots can contain credentials, personal data, or confidential documents.
- For repeatable server images, move capture to a headless browser rather than asking every visitor to run a large client render.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. One request returns a PNG, JPEG, WebP, or PDF. Before capture it accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether it was billed. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.
See the ScreenshotNeo API documentation for all 63 options, including full-page lazy-image loading, CSS-selector elements, dark mode, device presets, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparency, resizing, chosen-TTL caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data, and OpenAPI. Existing parameter names used by other screenshot APIs also work.
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)
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}`);
The Free plan includes 1,000 shots per month with no card. Starter is $5 for 3,000; Growth $15 for 15,000; Pro $39 for 60,000; Scale $99 for 250,000; and Business $249 for 1,000,000. Yearly billing gives two months free, and every feature is on every plan. Create a free ScreenshotNeo account to start.
Free tools Windows power users keep installed
One-click scans. No signup required.
Frequently Asked Questions
Can JavaScript capture a screenshot without asking the user?
Only DOM reconstruction of content your page can read can run without a display-sharing prompt. Capturing a tab, window, or monitor with getDisplayMedia() always requires activation, permission, and user selection.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Why does my screenshot differ from the page?
html2canvas reconstructs pixels from DOM and supported styles, so unsupported CSS, cross-origin resources, iframes, fonts, and timing can change the result. Use display capture when literal rendered pixels are required.
Can I capture a cross-origin iframe?
Not with html2canvas from the parent page. Browser same-origin rules prevent access to the iframe document; capture it from its own origin or use a user-selected display surface.
Quick Recap
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.
Recommended Free Tools

