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

To upload an html2canvas screenshot, render the target element, convert the returned canvas to a binary Blob, append that blob to FormData, and send it with fetch to an authenticated multipart endpoint. The browser sets the multipart boundary for you, so do not add a manual Content-Type header.

This workflow keeps image data binary, lets your server enforce size and type limits, and works with any storage system your application chooses. The endpoint URL, authentication method, maximum size, storage name, and response format are application decisions—not html2canvas features.

Complete browser-to-server example

Install the package used by your project and import it. The current package name is @html2canvas/html2canvas; use the version and package manager standardized by your application.

npm install @html2canvas/html2canvas

The following function captures #capture as a PNG and uploads it to /api/screenshots. Replace that path with your authenticated endpoint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Lexar D40E 128GB Dual USB 3.2 Gen 1 Type-C Jump Drive, Champagne Silver
  • USB-C 2-in-1 storage OTG: The Lexar JumpDrive Dual Drive D40E features USB Type-A and Type-C connectors in a slim, portable form factor for easy device compatibility
  • Transfer speeds up to 100MB/s: Based on internal testing, performance may vary depending upon the host device, interface, and usage conditions. 1MB=1,000,000 bytes
  • Plug and Play: Widely compatible with USB Type-C smartphones, tablets, laptops, Macs, and traditional Type-A devices, no software installation required. The 360° swivel design allows for easy switching between connectors without the hassle of losing a cap
  • Durable & Compact: The Lexar D40E USB memory stick features a metal enclosure, withstands temperatures from 0° to 50° C (32°F to 122°F), and is lightweight at 26g with dimensions of 70.4 x 16.9 x 11.7mm
  • Security & Warranty: Securely protects files using an advanced security software solution with 256-bit AES encryption. Backed by a Lexar 3-year limited warranty
import html2canvas from '@html2canvas/html2canvas';

async function uploadScreenshot() {
  const element = document.querySelector('#capture');
  if (!element) throw new Error('Capture target not found');

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

  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('screenshot', blob, 'screenshot.png');

  const response = await fetch('/api/screenshots', {
    method: 'POST',
    body: form,
    credentials: 'same-origin'
  });
  if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
  return response.json();
}

Call uploadScreenshot() from a button handler or another user action. credentials: 'same-origin' sends same-site cookies; use the authentication scheme required by your API if it is different.

Why the Blob step matters

canvas.toBlob() produces a binary file-like object without expanding the image into a long text string. The callback can return null, so the example rejects explicitly instead of uploading an invalid value. The filename passed to form.append is only a client hint; the server must not trust it for storage or type validation.

Do not set multipart Content-Type yourself

When fetch receives a FormData body, the browser adds a boundary such as multipart/form-data; boundary=…. Setting Content-Type: multipart/form-data manually omits that boundary in many clients and causes parsers to reject the request.

Capture the right element and control the output

Pass the specific DOM element you want, not the selector string. html2canvas reconstructs the element from DOM nodes and styles; it does not capture the browser compositor’s final output. Unsupported CSS, plugins, and browser-specific behavior can therefore produce an image that differs from what the user sees. The project describes the result as a browser-side “screenshot” and cautions that it may not be 100% accurate to the real representation.

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.

Quality, crop, and viewport options

  • scale: The documented default is the browser’s device-pixel ratio. A higher value can sharpen output but increases memory use, processing time, and upload size.
  • backgroundColor: Set a known color such as #ffffff for predictable PNGs, or use null when transparency is required and the downstream format supports it.
  • x, y, width, height: Capture a region rather than the whole element when a full-page image is unnecessary.
  • windowWidth and windowHeight: Choose the viewport used to evaluate media queries. This is useful when the capture must represent a fixed responsive breakpoint.
  • imageTimeout: Increase the image-loading timeout for slow assets, or disable it only when your application accepts potentially long captures.
  • data-html2canvas-ignore and ignoreElements: Exclude controls, transient notices, or sensitive fields from the image.

For example, this configuration captures a fixed-width region, hides elements marked for exclusion, and keeps a transparent background:

const canvas = await html2canvas(document.querySelector('#capture'), {
  x: 0,
  y: 0,
  width: 1200,
  height: 800,
  windowWidth: 1200,
  windowHeight: 900,
  backgroundColor: null,
  ignoreElements: element => element.matches('[data-private], .temporary-button'),
  imageTimeout: 20000,
  useCORS: true
});

Do not combine an extremely large scale with a large element unless you have measured browser memory and request-size limits. A capture can fail before the network request is made if the canvas cannot be allocated.

Rank #2
SANDISK 128GB Ultra Flair, USB-A Flash Drive, Up to 150MB/s Read Speeds
  • High-speed USB 3.0 performance of up to 150MB/s(1) [(1) Write to drive up to 15x faster than standard USB 2.0 drives (4MB/s); varies by drive capacity. Up to 150MB/s read speed. USB 3.0 port required. Based on internal testing; performance may be lower depending on host device, usage conditions, and other factors; 1MB=1,000,000 bytes]
  • Transfer a full-length movie in less than 30 seconds(2) [(2) Based on 1.2GB MPEG-4 video transfer with USB 3.0 host device. Results may vary based on host device, file attributes and other factors]
  • Transfer to drive up to 15 times faster than standard USB 2.0 drives(1)
  • Sleek, durable metal casing
  • Easy-to-use password protection for your private files(3) [(3)Password protection uses 128-bit AES encryption and is supported by Windows 7, Windows 8, Windows 10, and Mac OS X v10.9 plus; Software download required for Mac, visit the SanDisk SecureAccess support page]

Upload alternatives: PNG, JPEG, and base64

Binary PNG or JPEG with toBlob

PNG is lossless and is a sensible default for interface screenshots, text, and transparency. If transparency is not needed and smaller files are more important, request JPEG and provide a quality value:

const blob = await new Promise((resolve, reject) =>
  canvas.toBlob(
    file => file ? resolve(file) : reject(new Error('Canvas export failed')),
    'image/jpeg',
    0.85
  )
);

Match the filename extension to the MIME type you request. The server should still inspect the decoded bytes rather than trusting either value.

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

Data URL for APIs that explicitly require base64

The data-URL form is convenient when an API accepts JSON text, but it is less efficient for ordinary file uploads because binary data is expanded into encoded text.

const dataUrl = canvas.toDataURL('image/png');
await fetch('/api/screenshots/base64', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({ image: dataUrl })
});

Only remove the data:image/png;base64, prefix when the receiving API explicitly requires raw base64. Otherwise preserve the complete data URL or use a Blob endpoint.

Design the receiving endpoint safely

Your server is receiving untrusted input. A robust endpoint should:

  1. Authenticate and authorize the request before accepting the file.
  2. Apply a request-size limit and a decoded-image-size limit.
  3. Parse the multipart field named screenshot (or the name you selected).
  4. Verify the actual image type by decoding the bytes; do not rely on the filename or declared MIME type.
  5. Generate a safe storage key rather than using the client-provided filename.
  6. Store the object with the access policy your application requires.
  7. Return a small, explicit JSON result, such as an application-generated ID and URL, or a clear error code.

Keep the upload response separate from image processing if resizing, scanning, or moderation may take time. A short success response also prevents clients from depending on storage-provider-specific metadata.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
2 Pack 64GB USB Flash Drive USB 2.0 Thumb Drives Jump Drive Fold Storage Memory Stick Swivel Design - Black
  • What You Get - 2 pack 64GB genuine USB 2.0 flash drives, 12-month warranty and lifetime friendly customer service
  • Great for All Ages and Purposes – the thumb drives are suitable for storing digital data for school, business or daily usage. Apply to data storage of music, photos, movies and other files
  • Easy to Use - Plug and play USB memory stick, no need to install any software. Support Windows 7 / 8 / 10 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, compatible with USB 2.0 and 1.1 ports
  • Convenient Design - 360°metal swivel cap with matt surface and ring designed zip drive can protect USB connector, avoid to leave your fingerprint and easily attach to your key chain to avoid from losing and for easy carrying
  • Brand Yourself - Brand the flash drive with your company's name and provide company's overview, policies, etc. to the newly joined employees or your customers

Example response contract

// success
{
  "id": "generated-by-your-server",
  "url": "https://your-app.example/images/generated-key.png"
}

// failure
{
  "error": "image_too_large"
}

These values are examples of an application-defined contract. They are not supplied by html2canvas and must be implemented by your API.

Cross-origin images and blank or tainted exports

Cross-origin images are the most common reason an export is blank, incomplete, or unreadable. Setting useCORS: true helps only when the image server sends suitable CORS headers. If the remote server does not permit the browser origin, the image cannot be safely read back from the canvas.

Use CORS headers when you control the image host

Configure the image response to allow the requesting origin, then keep useCORS: true. The exact header policy depends on whether credentials are involved. Avoid allowing every origin by habit when the asset is private.

Use a controlled proxy when the source cannot provide CORS

The documented proxy option can point to a proxy under your control. That proxy must fetch the resource and return it in a form the browser can read. Protect it against open-proxy abuse, restrict allowed destinations, apply timeouts and response-size limits, and avoid forwarding private network requests.

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

Understand iframe limits

A cross-origin iframe cannot be rendered because its contentDocument is inaccessible to the page. You cannot bypass that browser security boundary by changing html2canvas options. Capture content that your page is allowed to read, or generate the image in a server-side browser that has access under an appropriate authorization model.

Prevent an already-tainted canvas

If any cross-origin content without usable CORS rules has been drawn, reading it with toBlob or toDataURL can throw a security error. Fix the source, proxy it safely, or exclude the asset before drawing; exporting after the fact cannot untaint the canvas.

Rank #4
SIMMAX 32GB Memory Stick USB 2.0 Flash Drives Swivel Thumb Drive Pen Drive (32GB Purple)
  • GOOD VALUE PACKAGE - 1 Pack 32GB Memory Stick USB 2.0 Flash Drives with great cost performance and high quality.
  • BIG CAPACITY - The available capacity: 29.10GB-29.8GB, You can save the data of movies, music, photos, designs, programs, manuals, handouts in a high speed.Good performance in digital data storing, transferring and sharing with families, friends, workmates, clients and machines.
  • EASY TO USE & PLUG AND WORK - Support windows 7 / 8 / 10 / Vista / XP / 2000 / ME / NT Linux and Mac OS, Compatible with USB2.0 and below.
  • TWISTTURN DESIGN & EASY CARRY - The metal clip rotates 360° round the ABS plastic body which with rubber oil skin feeling finish. The capless design can avoid lossing of cap, and providing efficient protection to the USB port.
  • WARRANTY & SUPPORT - SIMMAX logo is laser printed on the USB connector surface, our products are of good quality and we promise that any problem about the product within one year since you buy.

Common failures and fixes

Symptom Likely cause Fix
Capture target not found The selector ran before the element existed or is misspelled. Call the function after rendering, verify the selector in developer tools, and handle a missing target explicitly.
Blank image or missing remote images Cross-origin resources lack suitable CORS headers or have not finished loading. Enable useCORS, configure the asset host, or use a secured proxy; increase imageTimeout only for slow but permitted assets.
Security error while exporting The canvas was tainted by unreadable cross-origin content. Resolve CORS/proxy access before drawing. Re-render after fixing the source.
Text, shadows, or layout differs from the page html2canvas reconstructs supported DOM and CSS rather than capturing compositor pixels. Check supported styles, simplify the capture, or use browser automation when pixel fidelity to the rendered page is mandatory.
Upload returns 400 or the server says no file was found Field name mismatch or malformed multipart boundary. Make the server read screenshot, pass FormData directly, and remove any manually set multipart Content-Type.
413 Payload Too Large or browser memory failure Element dimensions or scale produce an oversized image. Crop with width/height, lower scale, choose JPEG where appropriate, and align client and server limits.
toBlob returns null The browser could not encode the requested format or the canvas is unusable. Reject the result, verify canvas dimensions and format, and retry with a supported type.
Capture waits indefinitely Slow assets, never-ending network activity, or an overly generous timeout. Set a bounded imageTimeout, ensure assets resolve, and cancel the surrounding operation when your UI no longer needs it.

When html2canvas is the wrong capture method

html2canvas is useful when the capture must happen in the user’s browser, should include the current DOM state, and should not require sending the page to a server for rendering. It also lets your application hide sensitive or transient elements before export.

A browser-automation screenshot is a better fit when you need pixels close to the browser’s compositor output, must capture cross-origin content from a controlled server context, or need generation without user interaction. That approach adds a server/runtime, browser lifecycle, and authorization design. Neither method removes the need to validate uploaded output if a client sends the file to your API.

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

Performance, reliability, and privacy checklist

  • Capture only the smallest element and region that meets the requirement.
  • Use the device-pixel-ratio default first; increase scale only after checking memory and upload size.
  • Wait until fonts, images, and application data needed by the target are ready.
  • Exclude controls and private fields with data-html2canvas-ignore or ignoreElements.
  • Set bounded client and server timeouts and show a retryable error to the user.
  • Keep authentication on the upload endpoint and apply CSRF protection when cookie authentication is used.
  • Log a request ID and server-side validation result, not the image contents or sensitive form values.
  • Test responsive breakpoints, slow images, blocked images, long pages, and browsers your users actually support.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server for developers. One request returns a PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

Use the API documentation at https://screenshotneo.com/docs/. cURL:

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}`);

ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Features include full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification.

Plans include 1,000 screenshots a month free with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account.

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

FAQ

Can I upload the canvas directly instead of creating a Blob?

No. FormData needs a file-like value, so convert the canvas with toBlob. Use a data URL only when the receiving API explicitly expects base64 text.

Best Value
Sale
IMEASON Swivel Design 16GB USB Flash Drive with Keychain, USB 2.0 Portable Thumb Drive Memory Stick, FAT32 Format Flashdrive for Data Storage, Photos, Music, Files (Black, 16 GB)
  • 【16GB Flash Drive】USB flash drives with 16GB capacity, meet your needs of daily use on work, school, home and travelling for photos, music, videos, files storage and transfer. IMEASON thumb drives can be used to store different files, easy to data backup.
  • 【Metal Swivel Cap Design】USB thumb drive is metal swivel cover provides extra protection for the usb thumbdrive connector, no usb drive cap to lose; keychain design makes it easier to carry without worrying lose it.
  • 【Wide Compatibility】USB drive supports Windows 7/8/10/11 / Vista / XP / Unix / 2000 / ME / NT Linux and Mac OS, also Supports USB 2.0 and 1.1 ports. USB Stick support TV, desktop, notebook computer, car, audio and other device. The USB Memory Stick is your great data storage and transfer companion with traveling and working.
  • 【Easy to use】usb memory stick is plug and play without any software installation. Just simply plug the Flashdrive into the port of your USB-compatible devices such as computer, laptop to start data storage or transmission.
  • 【What You Get】16 GB USB Flash Drive Thumb Drive, The default format of the usb storage flash drive is FAT32.

Will html2canvas capture a cross-origin iframe?

No. A cross-origin iframe’s document is inaccessible to the page, so html2canvas cannot reconstruct it.

Should screenshots be stored under the filename sent by the browser?

No. Treat the filename as untrusted metadata and generate a storage key on the server after validating the decoded image.

Is a higher scale always better?

No. It can improve detail while increasing memory use and upload size; choose the smallest value that meets your display or print requirement.

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

Frequently Asked Questions

Can I upload the canvas directly instead of creating a Blob?

No. Convert it with toBlob for a FormData file upload; use a data URL only when an API specifically requires base64 text.

Will html2canvas capture a cross-origin iframe?

No. Browser same-origin rules prevent access to the iframe document.

Should I trust the filename sent by the browser?

No. Validate decoded bytes and generate a server-side storage key.

Is a higher scale always better?

No. Higher scale can improve detail but increases memory use and upload size.

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.

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.