Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
Canvas

How to Store a Screenshot Created With html2canvas

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

html2canvas(element) gives you a Promise that resolves to an HTMLCanvasElement; it does not create a saved file by itself. For a quick local PNG, export the canvas with toDataURL('image/png'), put that URL on an anchor with a download filename, and trigger the anchor. For large images or an upload, use toBlob() and an object URL instead.

What html2canvas actually returns

html2canvas runs in the browser and reconstructs a visual representation of a DOM element. Its main function returns a Promise, so the export code must run after the Promise resolves:

const canvas = await html2canvas(document.querySelector('#capture'));

The canvas is an in-memory bitmap. Saving it is a separate step. You can download it in the browser, pass a Blob to your own server or storage API, or keep it in memory for another operation. There is no required server-side storage step for a local download.

Download a PNG with the shortest working method

Assuming html2canvas has already been loaded on the page, this function captures an element and starts a browser download:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
  • Easily store and access 2TB to content on the go with the Seagate Portable Drive, a USB external hard drive
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.
async function downloadPng(element, filename = 'screenshot.png') {
  const canvas = await html2canvas(element);
  const link = document.createElement('a');
  link.download = filename;
  link.href = canvas.toDataURL('image/png');
  link.click();
}

downloadPng(document.querySelector('#capture'));

The anchor does not have to be inserted into the document for this basic pattern. Set a filename ending in .png; the browser handles the download using the generated data URL. A complete button example looks like this:

document.querySelector('#save').addEventListener('click', async () => {
  const target = document.querySelector('#capture');
  if (!target) return;

  const canvas = await html2canvas(target);
  const link = document.createElement('a');
  link.download = 'profile-card.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
});

Use this approach when the image is modest in size and the user needs an immediate local file. The entire encoded image is held in a JavaScript string while the link is used, so it is not the best handoff for very large canvases.

Choose between toDataURL() and toBlob()

Use toDataURL() for a simple download

HTMLCanvasElement.toDataURL() encodes the complete image as a data URL. It keeps the code short and works well for a one-off PNG download, but the encoded string can consume substantial memory and can run into URL-size limits as the canvas grows.

Use toBlob() for large images and uploads

toBlob() creates a Blob representing the canvas image. Create a temporary object URL for a download, then revoke it after the browser has had time to consume it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
async function downloadPngAsBlob(element, filename = 'screenshot.png') {
  const canvas = await html2canvas(element);

  canvas.toBlob((blob) => {
    if (!blob) {
      throw new Error('The browser could not encode the canvas.');
    }

    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.download = filename;
    link.href = url;
    link.click();

    setTimeout(() => URL.revokeObjectURL(url), 1000);
  }, 'image/png');
}

downloadPngAsBlob(document.querySelector('#capture'));

Revoking the object URL releases the browser-side reference when it is no longer needed. This is the preferred path when the next step is an upload, because a Blob can be placed directly in a request body or a FormData object without first creating a large base64 string.

Rank #2
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
  • Easily store and access 1TB to content on the go with the Seagate Portable Drive, a USB external hard drive.Specific uses: Personal
  • Designed to work with Windows or Mac computers, this external hard drive makes backup a snap just drag and drop. Reformatting may be required for Mac
  • To get set up, connect the portable hard drive to a computer for automatic recognition no software required
  • This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable
  • The available storage capacity may vary.

Format and quality choices

Format When to use it Important behavior
PNG Interfaces, text, diagrams and transparency Dependable default and the required canvas export format
JPEG Photographic content where a smaller file is useful Accepts a quality value from 0 to 1 where the browser supports it; it does not preserve transparency
WebP When your supported browsers accept WebP encoding Can reduce size, but encoder support is not universal

For example, a JPEG export can request a quality value:

canvas.toBlob((blob) => {
  // upload or download blob
}, 'image/jpeg', 0.85);

PNG remains the safest default when you do not control the browser mix or need transparent pixels.

A reusable save function with error handling

Production code should check that the target exists, handle html2canvas rejection, and report an encoding failure instead of silently doing nothing:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
async function saveElementScreenshot(selector, filename = 'screenshot.png') {
  const element = document.querySelector(selector);
  if (!element) {
    throw new Error(`No element matches ${selector}`);
  }

  try {
    const canvas = await html2canvas(element);

    await new Promise((resolve, reject) => {
      canvas.toBlob((blob) => {
        if (!blob) {
          reject(new Error('Canvas encoding returned no Blob.'));
          return;
        }

        const objectUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.download = filename;
        link.href = objectUrl;
        link.click();
        setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
        resolve();
      }, 'image/png');
    });
  } catch (error) {
    console.error('Screenshot failed', error);
    throw error;
  }
}

saveElementScreenshot('#capture', 'account-summary.png');

The Promise around toBlob() makes it possible for calling code to show a success or failure message. It also keeps the export step distinct from the DOM capture step, which makes it easier to replace a download with an upload later.

Upload the screenshot for durable storage

If the image must survive a page refresh or be available to other users, treat the Blob as the upload payload for your own server or storage API. html2canvas creates the image; your application decides where and how it is stored. The exact provider, endpoint, authentication and retention policy are application architecture choices, not html2canvas requirements.

Rank #3
Sale
WD 2TB Elements Portable External Hard Drive for Windows, USB 3.2 Gen 1/USB 3.0 for PC & Mac, Plug and Play Ready - WDBU6Y0020BBK-WESN
  • High capacity in a small enclosure – The small, lightweight design offers up to 6TB* capacity, making WD Elements portable hard drives the ideal companion for consumers on the go.
  • Plug-and-play expandability
  • Vast capacities up to 6TB[1] to store your photos, videos, music, important documents and more
  • SuperSpeed USB 3.2 Gen 1 (5Gbps)
async function uploadElementScreenshot(element) {
  const canvas = await html2canvas(element);

  const blob = await new Promise((resolve, reject) => {
    canvas.toBlob((value) => {
      if (value) resolve(value);
      else reject(new Error('Could not encode canvas'));
    }, 'image/png');
  });

  const form = new FormData();
  form.append('file', blob, 'screenshot.png');

  const response = await fetch('/api/screenshots', {
    method: 'POST',
    body: form
  });

  if (!response.ok) {
    throw new Error(`Upload failed with HTTP ${response.status}`);
  }

  return response;
}

uploadElementScreenshot(document.querySelector('#capture'));
  • Authenticate the upload endpoint using your application’s normal session or token mechanism.
  • Validate the MIME type and size on the server; do not trust only the filename supplied by the browser.
  • Choose retention, access control and deletion behavior deliberately if screenshots contain personal or confidential data.
  • Return an identifier or URL from your endpoint so the application can find the stored object later.

Cross-origin assets and blank exports

Images from another origin

A canvas can become tainted when it includes an image that the browser loaded without permitting the required cross-origin access. A later export can then fail or raise a SecurityError. html2canvas documents a useCORS option and a proxy option for resources that cannot be loaded same-origin:

const canvas = await html2canvas(document.querySelector('#capture'), {
  useCORS: true
});

useCORS is not a way to bypass the browser’s security policy. The image server still has to allow the request with suitable CORS headers. A proxy must be an endpoint you control or trust; html2canvas does not supply your storage service or proxy configuration.

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

Cross-origin iframes

html2canvas cannot render a cross-origin iframe because the page is not allowed to read that frame’s contentDocument. If the content is in an iframe hosted on another origin, capture the content from that origin with an authorized workflow or redesign the page so the required DOM is available to the capturing document.

Why the result may not match a browser screenshot

html2canvas does not take a native, pixel-for-pixel browser screenshot. It traverses the DOM and builds a representation from the properties it understands. Unsupported CSS, browser-rendered details and external content can therefore look different even when the page itself appears correct.

Performance and memory guidance

  • Use toDataURL() when simplicity matters and the canvas is reasonably sized.
  • Use toBlob() for large canvases, repeated captures and uploads so the whole encoded image does not have to live in a JavaScript string.
  • Revoke object URLs after a download or preview is finished.
  • Do not create multiple full-size data URLs unnecessarily; release references to canvases and Blobs when the operation is complete.
  • Wait for the capture Promise before exporting. If your page is still changing, capture after the target has reached the visual state you want.

There is no universal file-size or speed figure for html2canvas: output depends on the element’s dimensions, its assets, browser implementation and the CSS that must be reconstructed.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting checklist

The download does nothing

Check that the selector found an element, that the code runs from a user-initiated click where your browser requires one, and that html2canvas is loaded before the handler executes. Log the Promise rejection rather than swallowing it.

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.

The image is blank or export throws SecurityError

Look for cross-origin images, canvas elements or other resources in the target. Remove the offending asset to confirm the cause, then configure the resource server for CORS and try useCORS: true, or route the resource through a suitable proxy. A cross-origin iframe cannot be made readable merely by changing the export format.

Some images are missing

Confirm that the images were loaded before capture and that their servers permit the required cross-origin request. If the page depends on an iframe from another origin, html2canvas cannot read its document.

The output looks different from the page

That is expected when the page uses CSS or browser-rendered effects that html2canvas does not support. Compare the generated representation with the DOM and simplify or replace unsupported styling when exact output matters.

toBlob() returns null

Handle a null Blob as an encoding failure. Try PNG first, verify that the canvas is valid, and check the browser’s memory pressure. Do not create an object URL until a real Blob has been returned.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
UnionSine 1TB Ultra Slim Portable External Hard Drive HDD-USB 3.0
  • 【Upgraded version】 - The mirror logo strip is combined with the striped non-slip design. The rounded corners of the shell are more suitable for holding. The strips play a heat dissipation function to ensure a stable and fast transmission process.
  • 【Ultra-thin and quiet】 - The motherboard adopts JMicron 578 noise-free solution, giving you a quiet working environment. Lightweight and portable size designed to fit in your pocket for easy portability.
  • 【Ultra-Fast Data Transfers】 - Pairing this external hard drive with JMicron 578 solution USB 3.0 and USB 2.0 interfaces enables blazing-fast data transfer. It boasts theoretical read speeds of up to 125MB/s and write speeds of up to 103MB/s.
  • 【Plug and Play】 - With no software to install, just plug it in and the drive is ready to use.The hard disk chip is wrapped with an aluminum anti-interference layer to increase heat dissipation and protect data.
  • 【What You Get】 - 1 x Portable Hard Drive, 1 x USB 3.0 Cable, 1 x User Manual, Gift-type shell packaging ,Three-year manufacturer's warranty and free technical support services.

A large screenshot makes the tab slow

Replace a data-URL export with toBlob(), avoid retaining old canvases and revoke every object URL after use. If the page still cannot handle the dimensions, capture a smaller target or move URL-based capture to a server-side service.

Or skip the browser setup

If your goal is a screenshot of a publicly reachable web page rather than a DOM element already inside the user’s tab, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP or PDF. It is a different workflow from html2canvas: you send a URL, and the service renders that page instead of exporting a canvas in your current browser.

ScreenshotNeo is useful when you need clean captures at a repeatable URL. Before capture it accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and each response identifies the result with X-Page-Verdict and X-Billed headers.

The API also supports full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or any viewport, retina scale, PDF paper size and margins, custom CSS and JavaScript, clicks before capture, hidden selectors, selector/delay/network-idle waits, request and resource blocking, custom headers, cookies, user agents and Authorization, timezone and geolocation, transparent backgrounds, image resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Parameter names used by other screenshot APIs work as well, which can simplify migration. An MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

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

Use the ScreenshotNeo documentation for the complete parameter list. The basic call is:

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 has the same features on every plan. Current monthly options are:

Plan Allowance Price
Free 1,000 shots $0, no card
Starter 3,000 shots $5
Growth 15,000 shots $15
Pro 60,000 shots $39
Scale 250,000 shots $99
Business 1,000,000 shots $249

Yearly billing gives two months free. The free tier includes 1,000 screenshots each month without a card, and paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try the URL-based workflow.

Frequently Asked Questions

Can html2canvas save directly to a database without a server request?

No. It can produce a canvas, data URL or Blob in the browser. Durable, shared storage requires your application to send the image to a server or storage API that you operate or select.

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

When should I use a URL screenshot service instead of html2canvas?

Use html2canvas when the target DOM is already inside the current page and client-side capture is acceptable. Use a URL screenshot service when you need an independent render of a web address, repeatable server-side jobs or automation from an AI agent.

Quick Recap

SaleBestseller No. 1
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
Seagate 2TB Portable Hard Drive | USB 3.0 (STGX2000400)
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.99
Bestseller No. 2
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
Seagate Portable 1TB External Hard Drive HDD – USB 3.0 for PC, Mac, PlayStation, & Xbox, 1-Year Rescue Service (STGX1000400) , Black
This USB drive provides plug and play simplicity with the included 18 inch USB 3.0 cable; The available storage capacity may vary.
$119.80
SaleBestseller No. 3

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 *

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.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.