Use the browser for capture and PHP for storage. For an HTML element or page region, render the DOM with html2canvas, export the canvas with toBlob(), upload the resulting file through fetch() and FormData, then validate its MIME type and move it with PHP’s move_uploaded_file(). If you need the user’s actual screen, window or tab instead, use navigator.mediaDevices.getDisplayMedia(); it requires HTTPS and explicit permission.
Choose what “screenshot” means
There are two different browser jobs, and choosing the wrong API is the most common source of disappointing results.
Capture an HTML element or page region
html2canvas reconstructs visible DOM information into a canvas. It is suitable for a report, dashboard, invoice, chart or selected page section. It does not capture browser chrome and is not guaranteed to match every composited layer pixel for pixel. CSS effects, embedded content and cross-origin images can differ from the live display.
Capture the actual display
getDisplayMedia() asks the user to choose a screen, window or browser tab. The returned MediaStream is assigned to a video element, then one video frame is drawn into a canvas. The call must occur from a user action such as a button click, runs in a secure HTTPS context, and is not available with equal support in every browser.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →#1 Best Overall
- 【1080P 60FPS Video Capture Card】 This HDMI game capture card is based on USB3.0 high speed transmission port, input resolution up to 4K@30HZ, output resolution up to 2K@30Hz or 1920×1080@60Hz. Type c and USB interface can meet most of the devices in daily life. Easily meet the online capture, real-time recording, online meetings, live gaming and other functions, so you have a better visual enjoyment. Note: For capture use only; requires capture software to function and is not intended for direct screen casting to a monitor or TV
- 【Ultra Low Latency Screen Sharing】 HDMI capture card is made of good quality aluminum alloy with strong heat dissipation, allowing you to enjoy ultra low latency while live gaming or video recording or live streaming, avoiding blue screens and lag. This HDMI to USBC capture card supports easy recording of good quality audio or HD video and transferring it to your computer or streaming platform, allowing you to record 60 fps HD video directly on your hard drive and real-time preview
- 【Plug and Play, Easy to Carry】 This HDMI 1080P video capture card does not require any additional drivers or external power supply, just plug and play for fast capture. The capture card is small and lightweight, so you can put it in your bag for emergencies, making it very portable for outdoor live streaming. It's also a great way to share content in game recording, video conference, video recorder and online teaching
- 【Wide Compatibility USB Capture Card】 Easily streams to Facebook, Youtube or Twitch. With the connection, this HDMI to USB C/3.0 video capture devices can be working on several Operating Systems and various software: Windows 7/ 8/ 10, Mac OS or above, Linux, Android, Laptop, Xbox One, PS3/PS4/PS5, Camera, DVDs, Set Top Box, Webcame, DSLR, Switch/Switch 2, TV BOX, HDTV, Potplayer/VLC, ZOOM, OBS Studio etc.
- 【Package Content & Note】 1x HD Audio Capture Card , 1x USB 3.0 to USB C Adapter (A-side 3.0, B-side 2.0), 1x user manual. Please note that you need to restart the OBS Studio software after the audio setup is complete, otherwise it will result in no sound output. When using an adapter, if the device is recognized as USB 2.0, try using the other side with the USB-C port. Simply flip the capture card and reconnect it to be recognized as USB 3.0
| Requirement | DOM capture | Display capture |
|---|---|---|
| API | html2canvas |
navigator.mediaDevices.getDisplayMedia() |
| Permission prompt | Usually none | Always user-selected permission |
| Target | Element or document DOM | Screen, window or tab stream |
| HTTPS | Recommended for site assets | Required |
| Fidelity | DOM reconstruction, not a true display shot | Actual rendered video frame |
| Cross-origin concern | Images without CORS can taint the canvas | Permission and browser support are the main constraints |
Complete DOM-element implementation
The following example captures #capture, creates a PNG Blob, posts it as a multipart upload and reports the filename returned by PHP.
HTML
<button id="save-shot" type="button">Save screenshot</button>
<div id="capture">
<h1>Monthly report</h1>
<p>This panel is the capture target.</p>
</div>
<p id="status" role="status"></p>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script src="app.js" defer></script>
JavaScript upload
const button = document.querySelector('#save-shot');
const status = document.querySelector('#status');
button.addEventListener('click', async () => {
button.disabled = true;
status.textContent = 'Rendering…';
try {
const canvas = await html2canvas(document.querySelector('#capture'), {
scale: window.devicePixelRatio,
useCORS: true,
backgroundColor: '#ffffff'
});
const blob = await new Promise((resolve, reject) => {
canvas.toBlob(result => result ? resolve(result) : reject(new Error('Canvas export failed')), 'image/png');
});
const form = new FormData();
form.append('shot', blob, 'screenshot.png');
status.textContent = 'Uploading…';
const response = await fetch('/save-screenshot.php', {
method: 'POST',
body: form,
credentials: 'same-origin'
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Upload failed');
status.textContent = `Saved as ${data.file}`;
} catch (error) {
status.textContent = error.message;
} finally {
button.disabled = false;
}
});
The scale option uses the device pixel ratio for sharper high-DPI output. useCORS: true only helps when the image server sends an appropriate CORS header; it cannot override another origin’s policy.
Rank #2
- [Enhanced 4K-1080P Video Capture Experience] Capture the Magic: Elevate your video recordings to new heights with our upgraded anti-static 1080P Video Capture Card. Immerse yourself in stunning visuals, supporting HDMI input at 4K 60FPS and USB output for capturing in 1080P, complete with rich stereo sound. Enjoy crystal-clear video recordings, dynamic gaming live streams, and professional conference broadcasts. Note: HDMI resolution: Max input can be 3840×2160@30Hz / Video output resolution: Max output can be 1920×1080@30Hz
- [Seamless Real-Time Preview] Stay in the Moment: Our advanced ultra-low latency technology ensures seamless real-time transmission of video streams. Experience instant, lag-free previews, allowing you to capture every detail precisely. Effortlessly record video directly to your hard disk, all without compromising on quality or introducing any delays.
- [Versatility and Broad Compatibility] Your Creative Hub: Connect your DSLR, camcorder, or action camera to a wide range of operating systems, including Windows, MacOS, and Linux. Unlock a world of possibilities with real-time streaming to popular platforms like Twitch, Youtube, OBS, Zoom, Potplayer, and VLC, giving you the tools to share your content effortlessly.
- [Effortless Plug and Play] Simplicity Redefined: Say goodbye to complex installations. Our plug-and-play design eliminates the need for drivers or external power supplies. Seamlessly integrate high-definition acquisition into various scenarios, whether it's educational recordings, immersive gaming, precise medical imaging, captivating live streams, or professional broadcasting.
- [Seize Every Detail with Precision] Unleash your creativity and attention to detail with our video capture card. Capture every nuance, every color, and every moment with precision, thanks to the enhanced capabilities of our technology. Whether you're a content creator, a gamer, or a professional, our capture card empowers you to seize the finest elements and bring them to life in your recordings and live streams.
Exporting the canvas safely
canvas.toDataURL('image/png') returns a base64 data URL and is convenient for a small download, but it creates the complete image as a large in-memory string. For uploads, toBlob() avoids that extra encoding step. PNG is the default lossless format; request JPEG or WebP when your browser and quality requirements allow smaller files.
// Optional local download
const link = document.createElement('a');
link.download = 'screenshot.png';
link.href = canvas.toDataURL('image/png');
link.click();
If a canvas contains pixels loaded from another origin without permission, reading or exporting it throws a security error because the canvas is tainted. Host the asset on the same origin, configure CORS on the asset server, or omit that asset from the capture.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchRank #3
- 【4K HDMI Input, 2K@30Hz Recording】Powered by a true USB 3.0 high-speed interface, the capture card supports up to 4K@30Hz HDMI input and records at 2K@30Hz or 1080P@60Hz. Perfect for gamers, streamers, and professionals who need crisp, smooth video for live streaming, gameplay recording, or online meetings.
- 【Ultra Low Latency Screen Sharing】Built with a premium aluminum alloy shell and advanced chipset for stable heat dissipation, ensuring ultra-low latency transmission. Capture high-quality video and dual-channel audio in real time—no lag, no frame drop—ideal for Twitch, YouTube, or OBS streaming.
- 【Easy Plug and Play, Compact & Portable】No driver or external power required—just plug and play via USB 3.0 or Type-C connection to your Windows or macOS computer. Lightweight and compact design makes it easy to carry for outdoor streaming, live shows, or mobile recording setups.
- 【Wide Compatibility & Multi-Device Support】Compatible with Windows 7 8 10 11, macOS, Linux,Android and supports most popular software such as OBS, Zoom, VLC, Twitch Studio, and more. Works seamlessly with PS4, PS5, Xbox, Switch, DSLR cameras, TV boxes, and other HDMI-output devices for streaming to YouTube, Twitch, etc.
- 【What You Get】Includes: HDMI Capture Card, USB 3.0 to USB-C Adapter, User Manual. Tips: Make sure your tablet’s OTG function is enabled before connecting. Test your HDMI device with a monitor first to confirm video and audio output, then connect to the Video Capture Card for recording.
Capture the user’s screen, window or tab
Use this path when “screenshot” means what the user can currently see rather than what your DOM contains.
<button id="share-screen" type="button">Capture screen</button>
<video id="preview" autoplay muted playsinline hidden></video>
<script>
const share = document.querySelector('#share-screen');
share.addEventListener('click', async () => {
let stream;
try {
stream = await navigator.mediaDevices.getDisplayMedia({
video: { displaySurface: 'browser' },
audio: false
});
const video = document.querySelector('#preview');
video.srcObject = stream;
await new Promise(resolve => video.onloadedmetadata = resolve);
await video.play();
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
const blob = await new Promise((resolve, reject) =>
canvas.toBlob(b => b ? resolve(b) : reject(new Error('Export failed')), 'image/png'));
const form = new FormData();
form.append('shot', blob, 'display.png');
const response = await fetch('/save-screenshot.php', { method: 'POST', body: form });
if (!response.ok) throw new Error('Server rejected the upload');
stream.getTracks().forEach(track => track.stop());
} catch (error) {
if (error.name === 'NotAllowedError') alert('Select a surface, or allow screen sharing.');
else alert(error.message);
if (stream) stream.getTracks().forEach(track => track.stop());
}
});
</script>
Invoke getDisplayMedia() directly in the click handler; browsers may reject calls made later by a timer or without transient user activation. Check navigator.mediaDevices before showing the control, explain the browser requirement, and provide the DOM-capture fallback when screen sharing is unavailable.
Rank #4
- 【1080P HD High Quality】Capture resolution up to 1080p for video source and it is ideal for all HDMI devices such as PS4, PS3, Xbox One, Xbox 360, Wii U, DVDs, DSLR, Camera, Security Camera and set top box. Note: Video input supports 4K30/60Hz and 1080p120/144Hz. Does not support 4K120Hz/144Hz. Output supports up to 2K30Hz.
- 【Plug and Play】No driver or external power supply required, true PnP. Once plugged in, the device is identified automatically as a webcam. Detect input and adjust output automatically. Won't occupy CPU, optional audio capture. No freeze with correct setting.
- 【Compatible with Multiple Systems】suitable for Windows and Mac OS. High speed USB 3.0 technology and superior low latency technology makes it easier for you to transmit live streaming to Twitch, Youtube, Facebook, Twitter, OBS, Potplayer and VLC.
- 【HDMI LOOP-OUT】Based on the high-speed USB 3.0 technology, it can capture one single channel HD HDMI video signal. There is no delay when you are playing game live.
- 【Support Mic-in for Commentary】Rybozen capture card has microphone input and you can use it to add external commentary when playing a game. Please note: it only accepts 3.5mm TRS standard microphone headset.
PHP endpoint: validate before saving
Never trust the filename or MIME value supplied by the browser. Reject malformed upload structures, enforce a size limit, inspect the temporary file with PHP’s Fileinfo extension, permit only formats you intend to serve, generate a random server-side name and store uploads outside an executable directory when possible.
<?php
header('Content-Type: application/json');
function fail(int $status, string $message): never {
http_response_code($status);
echo json_encode(['error' => $message]);
exit;
}
if (!isset($_FILES['shot']) || is_array($_FILES['shot']['error'])) {
fail(400, 'Malformed upload');
}
if ($_FILES['shot']['error'] !== UPLOAD_ERR_OK) {
fail(400, 'Upload error: ' . $_FILES['shot']['error']);
}
if ($_FILES['shot']['size'] > 5_000_000) {
fail(413, 'File exceeds the 5 MB limit');
}
$tmp = $_FILES['shot']['tmp_name'];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($tmp);
$extensions = [
'image/png' => 'png',
'image/jpeg' => 'jpg',
'image/webp' => 'webp'
];
$extension = $extensions[$mime] ?? null;
if ($extension === null) {
fail(415, 'Unsupported image type');
}
$directory = __DIR__ . '/uploads';
if (!is_dir($directory) && !mkdir($directory, 0750, true)) {
fail(500, 'Storage directory is unavailable');
}
$name = bin2hex(random_bytes(16)) . '.' . $extension;
$destination = $directory . '/' . $name;
if (!move_uploaded_file($tmp, $destination)) {
fail(500, 'Could not persist upload');
}
echo json_encode(['file' => $name]);
move_uploaded_file() accepts only files received through PHP’s HTTP POST upload mechanism and can overwrite an existing destination. Random names prevent collisions and avoid using attacker-controlled paths. Add authentication, CSRF protection, rate limiting, retention rules and access controls for a public application. Configure PHP’s upload_max_filesize and post_max_size above your application limit, while keeping the application check as the final policy.
Best Value
- AV TO USB Converter: Capture videos and audios from VHS, VCR, Hi8, DV tapes to a PC, with the help of our USB Video Converter. Save room while digitizing your favorite old memories
- Quality Capture Card: Our USB Video Capture Card converting anolog RCA composite input into HD 720P USB output and capturing audio without any sound card. Advanced signal processing technology provides you with great precision, colors, resolutions, and details.
- Plug and Play: Automatically install the driver once you hook up this RCA to USB Converter to a PC. No external power is needed. User-friendly and easy to operate
- Wide Compatibility: The Video Capture Card can work with video devices with RCA connector or S-Video connector, such as VHS, VCR, Hi8, camcorder, compatible with Windows and Mac OS. Support video formats like NTSC, PAL, and support brightness, contrast, hue, and saturation control
- Note: The Video Converter is used with acquisition software. We recommend OBS Studio or PotPlayer for Windows, and QuickTime Player for Mac. They can be downloaded for free online. Please operate according to the steps in User Manual or contact us if you have any questions
Quality, size and performance choices
- Large or full-page captures: prefer
toBlob(); a data URL duplicates memory and can exceed request limits. - Sharpness: device-pixel-ratio scaling improves detail but increases canvas dimensions, memory use and upload size. Cap the scale for very large regions.
- Format: PNG preserves text and transparency; JPEG is smaller for photographs but loses transparency; WebP can reduce size where your consumers support it.
- Long pages: lazy-loaded images may not be present when rendering. Scroll or otherwise load required content first, and wait for fonts and images.
- Server reliability: return JSON for both success and failure, set explicit HTTP status codes, and treat a successful HTTP response as valid only after parsing the JSON body.
Common failures and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Blank or incomplete element | Fonts, images or lazy content have not loaded | Wait for required resources and capture after the UI settles. |
| “Tainted canvas” or security exception | Cross-origin image lacks CORS permission | Serve it same-origin or configure the image server’s CORS headers; useCORS alone is insufficient. |
| Screen prompt never appears | Call was not made from a user gesture, or page is not HTTPS | Call directly from a click and deploy in a secure context. |
NotAllowedError |
User cancelled or denied surface selection | Explain the prompt and allow another attempt; do not retry invisibly. |
| HTTP 400 from PHP | Wrong field name or PHP upload error | Ensure the client uses form.append('shot', ...), inspect $_FILES['shot']['error'], and check PHP limits. |
| HTTP 415 | Fileinfo detected an unapproved type | Export PNG/JPEG/WebP and add only formats your application can safely process. |
| HTTP 500 on move | Missing directory or permissions | Create the directory with restricted permissions and give PHP’s worker write access. |
| Upload succeeds but file is unsafe to serve | Uploads are in an executable web path | Store outside executable paths, disable script execution there and serve through controlled download responses. |
Or skip the browser setup
When you need a screenshot of a public URL rather than a visitor’s private screen, ScreenshotNeo provides a single API request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result.
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 options such as full-page lazy-image loading, CSS-element capture, device presets, custom viewport and retina scale, PDF output, custom CSS or JavaScript, waits, request blocking, headers, cookies, geolocation, resizing, TTL caching, signed image links, asynchronous webhooks, bulk capture and usage reporting. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
Python
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)
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}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
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, and yearly billing gives two months free. Create a free ScreenshotNeo account.
Security and operational checklist
- Require HTTPS for screen capture and authenticated upload endpoints.
- Validate PHP’s upload error, byte size and Fileinfo MIME independently of browser metadata.
- Generate random names; never concatenate an uploaded filename into a path.
- Keep upload directories non-executable and define retention and deletion policies.
- Limit dimensions and request rates if users can submit many high-resolution images.
- Stop every display-capture track after the frame is drawn so the browser indicator and permission session end.
- Log failures without logging image contents or credentials.
Frequently Asked Questions
Can JavaScript capture the browser address bar or other browser chrome?
No. DOM capture sees page content, while display capture records only the surface the user explicitly selects; browser security does not expose unrestricted browser chrome.
Why is my screenshot different from what I see?
html2canvas rebuilds the DOM rather than taking a compositor-level picture. Unsupported CSS, unloaded resources and cross-origin images can therefore change the result.
Should I send a base64 string to PHP?
For small local previews it can be acceptable, but production uploads should use a Blob in multipart FormData to avoid the extra memory and decoding overhead of a data URL.
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.

