October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk9 min

How to Save an html2canvas Screenshot as a JPEG

Capture an element with html2canvas, encode the canvas as JPEG, download it safely, and fix CORS, memory and large-page failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call html2canvas() on the element, wait for the returned canvas, then encode it with canvas.toDataURL('image/jpeg', quality) and download the resulting data URL. Use a quality value from 0 to 1, give the link a .jpg filename, and set a solid background because JPEG cannot store transparency.

Save an element as JPEG: the working example

Include html2canvas in your page, identify the element to capture, and connect a button to this function. The example deliberately sets the important output options instead of relying entirely on defaults.

<button id="save-jpeg" type="button">Save JPEG</button>
<section id="capture">
  <h1>Invoice preview</h1>
  <p>This section becomes the downloaded image.</p>
</section>

<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
async function saveAsJpeg() {
  const element = document.querySelector('#capture');
  if (!element) throw new Error('The #capture element was not found');

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

  const link = document.createElement('a');
  link.download = 'screenshot.jpg';
  link.href = canvas.toDataURL('image/jpeg', 0.92);
  link.click();
}

document.querySelector('#save-jpeg').addEventListener('click', () => {
  saveAsJpeg().catch(console.error);
});
</script>

The promise resolves to a canvas after html2canvas reconstructs the selected element from its DOM and CSS. toDataURL() then asks the browser’s Canvas API for a JPEG string. The second argument, 0.92 here, is the encoder quality: 0 produces the smallest, poorest result and 1 requests maximum quality. The exact dimensions, file size and visual artifacts depend on the browser’s JPEG encoder.

What the download code is doing

Selecting the capture

document.querySelector('#capture') returns the first matching element. Check for a null result before calling html2canvas; otherwise a misspelled selector produces a confusing failure. You can pass any element reference, including one obtained from a framework ref.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Canon 7981A004 Photo Paper Plus, Matte, 8-1/2 x 11 (Pack of 50 Sheets)
  • Excellent photo results with vibrant colors.
  • Pack of 50 Sheets

Waiting for rendering

Use await html2canvas(element, options) (or a .then() callback). Starting the export before the promise resolves can create an incomplete result, especially when fonts, images or layout changes are still being processed.

Choosing JPEG output

The MIME string must be exactly image/jpeg. A filename ending in .jpg makes the browser’s download type and the user’s file manager agree with the encoded content. JPEG has no alpha channel, so transparent areas are flattened against the chosen background.

Starting the download

An anchor with a download attribute is the simplest browser-side download mechanism. Calling click() starts it in response to the button handler. If a browser blocks a synthetic click, append the link to the document, click it, and remove it immediately, or expose the link for the user to click.

Use toBlob() for large captures

A data URL keeps the complete encoded image in a JavaScript string. For large or very tall images that can consume substantial memory and create an unwieldy URL. toBlob() writes the encoded bytes to a Blob; an object URL points to those bytes without putting them all in the link text.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
async function saveLargeJpeg() {
  const canvas = await html2canvas(document.querySelector('#capture'), {
    backgroundColor: '#ffffff',
    scale: 1.5,
    useCORS: true
  });

  canvas.toBlob((blob) => {
    if (!blob) {
      throw new Error('The browser could not encode this canvas as JPEG');
    }
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.download = 'screenshot.jpg';
    link.href = url;
    link.click();
    URL.revokeObjectURL(url);
  }, 'image/jpeg', 0.92);
}

saveLargeJpeg().catch(console.error);

Use the object URL only while the download is being initiated. Revoking it immediately after click() works in current browsers; if a particular browser cancels the download, revoke it from a short setTimeout instead.

Rank #2
Sale
HP Everyday Photo Paper, Glossy, 8.5x11 in, 50 sheets (Q8723A)
  • Create affordable photo projects with a bright, glossy finish
  • Customize photos with easy-to-use editing tools and print from your phone with HP Smart app
  • Handle durable, quick-dry photos right from the printer
  • Make memories last with photos that resist fading for decades when printed with Original HP Ink

Options that control dimensions, clarity and content

Option Purpose Practical choice
scale Multiplies the rendered pixel dimensions. html2canvas defaults to window.devicePixelRatio. Set it explicitly, such as 1 for lower memory or 2 for a sharper export.
backgroundColor Fills the canvas background. Use '#ffffff' for JPEG. null preserves transparency in formats that support alpha, but JPEG will not.
useCORS Attempts to load remote images with CORS. Set true only when the image server sends an appropriate Access-Control-Allow-Origin header.
proxy Routes image loading through a server-side proxy. Use a same-origin proxy when third-party images cannot provide usable CORS headers.
x, y, width, height Crops the rendered region. Specify all four when you need a controlled crop rather than the element’s full box.
ignoreElements Excludes nodes programmatically. Return true for buttons, menus or other controls that should not appear.
data-html2canvas-ignore Marks individual nodes for exclusion. Add the attribute to a node in your markup when no JavaScript predicate is needed.

For a predictable export, wait until the element has its final size, fonts and images. If you need the whole document rather than the visible box, capture a wrapper containing the complete content and consider the viewport settings described below.

Remote images, CORS and tainted canvases

An image served from another origin can taint the canvas. Once tainted, browser security rules prevent reading pixels or exporting them, so toDataURL() or toBlob() may throw a security error. useCORS: true does not bypass that policy: the image server must opt in with a suitable Access-Control-Allow-Origin response header.

If you control the asset server, configure that header and ensure the image URL is reachable without a login redirect. If you do not control it, use a server-side proxy that fetches the image and serves it from an origin your page can access. Do not attempt to disable browser security; it is not a deployable fix. Cross-origin iframes are a separate limit: the browser does not expose their contentDocument, so html2canvas cannot reconstruct their contents.

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

Long pages and canvas-size limits

Capturing a very tall element at a high scale can exceed a browser’s maximum canvas dimensions or available memory. Symptoms include an empty image, a truncated bottom, an exception, or a tab that becomes unresponsive. Reduce scale, capture sections separately, or crop with x, y, width and height.

For a full-page-style capture, make the render viewport match the content dimensions when appropriate:

Rank #3
Sale
Reastar Glossy Photo Paper 8.5 × 11, 36 Sheets Inkjet Photo Printer Paper
  • Photo Paper Package: 36 sheets of glossy photo paper, 8.5×11 inch, industry standard 180gsm/48lb, single-sided printing and blank back side for recording or writing something; compatible with inkjet printers and dye ink
  • Glossy Finish: our glossy photo paper features its a reflective finish, that adds a professional and attractive touch and makes every picture look like a work of art; the printed photos and graphics are so outstanding
  • Leave Vivid Colors: thanks to the good ink absorption of the picture paper, the printed photos come out vibrant colors and sharp details that truly come to life; remain beautiful landscapes and impressive moments forever
  • Instant Dry: due to the advanced super cast coating, the ink on prints dry quickly without smearing and jamming; plus, the prints retain their vibrant color over time; makes your memories and designs shine in their full glory
  • Wide Application: perfect for printing photos to record important and sweet moments, and also ideal for printing detailed graphics, various greeting cards, posters, chip bags, flyers, brochures, calendars, baby book
const target = document.querySelector('#capture');
const canvas = await html2canvas(target, {
  windowWidth: target.scrollWidth,
  windowHeight: target.scrollHeight,
  backgroundColor: '#ffffff',
  scale: 1
});

That setting helps when responsive CSS depends on viewport size, but it does not remove browser canvas limits. Test the largest real page your users will export.

Know what html2canvas can and cannot reproduce

html2canvas is a browser library that reconstructs a representation from the DOM and CSS; it is not a native pixel screenshot. The result can differ from what the browser visually composites, and unsupported or complex CSS may not match exactly. It cannot circumvent content-policy restrictions, and it cannot render the inside of a cross-origin iframe. It runs in modern evergreen browsers and is not suitable for Node.js server execution.

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

These constraints matter for designs using external fonts, filters, video, canvas layers, blend modes or browser-specific effects. If exact browser pixels are required, use a browser automation capture rather than a DOM reconstruction library.

Quality, size and performance decisions

  • Quality: Start around 0.9 to 0.95. Lower values shrink files but make text edges and gradients show JPEG artifacts.
  • Scale: Increase it for retina-quality output only when memory and encode time permit. A larger scale increases both pixel count and work roughly with the area.
  • Format: JPEG is appropriate for photographic or opaque content. If you need transparency or crisp flat UI edges, encode a PNG instead.
  • Encoding path: Use toDataURL() for a short, simple export and toBlob() for large files.
  • UI responsiveness: Disable the export button while rendering, show progress for long captures, and restore the button in a finally block.

Troubleshooting common failures

The file downloads but is blank

Confirm that the selector found the intended element and that it has nonzero dimensions. Capture after the component is mounted and visible. For a long page, reduce the scale and inspect canvas-size limits.

“Tainted canvases may not be exported” or a security exception

Find the remote image responsible, enable useCORS, and verify its response includes the required CORS header. Otherwise route it through a same-origin proxy. Browser JavaScript cannot override the policy.

Rank #4
Sale
Epson Ultra Premium Photo Paper Glossy (8.5x11 Inches, 50 Sheets) (S042175),White
  • Long lasting, professional quality prints
  • Ultra smooth, bright white, heaviest weight paper
  • Fast drying, smudge and water resistant surface
  • The new standard for extraordinary images

Images are missing

Wait until images have loaded before calling html2canvas, use absolute reachable URLs, and configure CORS for cross-origin assets. A failed image request cannot be reconstructed later by the library.

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

The screenshot looks different from the page

Check unsupported CSS, cross-origin frames and responsive breakpoints. Set scale, windowWidth and windowHeight deliberately, and simplify effects that html2canvas cannot represent.

The browser tab freezes or the export fails on a dashboard

Lower scale, capture smaller regions, switch from toDataURL() to toBlob(), and avoid holding multiple canvases in memory. Revoke object URLs after each download.

The download does not start

Run the export from a user-initiated click, check that the anchor has both href and download, and try appending it to the document before clicking. Some browsers restrict downloads that are not tied to a user gesture.

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 provides a website screenshot API when you need a rendered page rather than a DOM reconstruction. A single request returns PNG, JPEG, WebP or PDF, and its capture can load lazy images, target an element by CSS selector, set a viewport or device preset, use retina scale, inject CSS or JavaScript, click before capture, wait for a selector, delay or network idle, hide selectors, block ads or resource types, set headers, cookies, user agent, timezone or geolocation, and more. It accepts the parameter names used by other screenshot APIs, which can simplify migration.

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.
Best Value
CAREGY 40 Sheets Single Sided Glossy Photo Paper for Inkjet, 8.5x11 Inches,
  • Reliable quality and large capacity: Made from high-quality 180GSM/48lb paper, with uniform thickness and a smooth surface. Standard letter size (8.5 x 11 inches / 216 x 279 mm), 40 sheets per pack
  • Fast Ink Absorption & Smudge-Proof Performance:Features advanced coating technology for ultra-fast ink absorption. It prints without smudging and reduces waiting time. Ensures crisp images right after printing, ideal for high-efficiency office and home use
  • Vibrant, True-to-Life Color Reproduction:Optimized for dye ink to deliver rich, vivid colors and accurate color matching. With outstanding color fidelity, it accurately captures every image detail, ensuring precise and vivid presentation of photos, flyers, and other printed materials
  • Single-Sided Glossy Finish for Stunning Visuals:Boasts a premium single-sided glossy surface that enhances color vibrancy and image clarity. Ink Absorbent Coating prevents ink penetration and ensures stable stacking, perfect for creating professional-looking prints without bulk.The blank back provides handy space for your notes or explanations
  • Versatile Application Scenarios for All Your Needs:Ideal for a wide range of uses, including photo printing, promotional flyers, product brochures, classroom handouts and home crafts (like DIY chip bags). Compatible with most inkjet printers, meeting both professional and personal printing demands
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 documentation for authentication, output options and the complete API reference. The same request in Python is:

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)

And in 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()));
  • Cookie and consent banners, newsletter popups and chat widgets are removed before the shot.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed; response headers identify the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Create a free ScreenshotNeo account to try it without a card.

FAQ

Can I save an html2canvas result as .jpg instead of .jpeg?

Yes. Both extensions describe JPEG. Set the anchor’s filename to either extension; the MIME type remains image/jpeg.

Does changing quality change the canvas dimensions?

No. Quality affects JPEG encoding and file size, while the element size and scale determine pixel dimensions.

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

Can html2canvas capture a page on the server?

No. It runs in the browser and depends on browser DOM, CSS and security policies. Use a browser-based capture service or automation tool for server-side jobs.

Frequently Asked Questions

Why is my JPEG larger than the original page image?

The export is a newly encoded bitmap. Pixel dimensions, scale, JPEG quality and the browser encoder—not the source page’s byte size—determine the resulting file size.

Should I use PNG instead of JPEG for text-heavy interfaces?

PNG preserves sharp edges and transparency, while JPEG is smaller for photographic or opaque content. Choose based on whether lossless edges or compact photographic output matters more.

Quick Recap

SaleBestseller No. 1
Canon 7981A004 Photo Paper Plus, Matte, 8-1/2 x 11 (Pack of 50 Sheets)
Canon 7981A004 Photo Paper Plus, Matte, 8-1/2 x 11 (Pack of 50 Sheets)
Excellent photo results with vibrant colors.; Pack of 50 Sheets
$7.19
SaleBestseller No. 2
HP Everyday Photo Paper, Glossy, 8.5x11 in, 50 sheets (Q8723A)
HP Everyday Photo Paper, Glossy, 8.5x11 in, 50 sheets (Q8723A)
Create affordable photo projects with a bright, glossy finish; Handle durable, quick-dry photos right from the printer
$16.99
SaleBestseller No. 4
Epson Ultra Premium Photo Paper Glossy (8.5x11 Inches, 50 Sheets) (S042175),White
Epson Ultra Premium Photo Paper Glossy (8.5x11 Inches, 50 Sheets) (S042175),White
Long lasting, professional quality prints; Ultra smooth, bright white, heaviest weight paper
$22.00

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.