To convert a rendered React element to a downloadable JPG in the browser, capture the element with html2canvas, encode the returned canvas with canvas.toDataURL('image/jpeg', quality), and trigger an anchor download. This approach is convenient for cards, invoices, certificates and other component-sized exports. It reconstructs the DOM rather than taking a native browser screenshot, so use Playwright or Puppeteer when exact browser rendering, cross-origin content or server-side generation matters.
Client-side conversion with html2canvas
Install the library in your React project:
npm install html2canvas
The component below captures one element after React renders it, requests a high-density canvas, converts it to a lossy JPEG at quality 0.92, and downloads the result.
import { useRef, useState } from 'react';
import html2canvas from 'html2canvas';
export function DownloadCard() {
const cardRef = useRef(null);
const [busy, setBusy] = useState(false);
async function downloadJpg() {
if (!cardRef.current || busy) return;
setBusy(true);
try {
const canvas = await html2canvas(cardRef.current, {
scale: window.devicePixelRatio,
useCORS: true,
backgroundColor: '#ffffff'
});
const link = document.createElement('a');
link.download = 'card.jpg';
link.href = canvas.toDataURL('image/jpeg', 0.92);
link.click();
} finally {
setBusy(false);
}
}
return (
<>
Content to export
This DOM element becomes a JPG.
>
);
}
The ref identifies the exact element. Calling html2canvas from the click handler ensures the component has mounted. scale equal to window.devicePixelRatio generally produces sharper output on high-density displays, but it also multiplies pixel dimensions and memory use. Reduce it to 1 for very large exports or memory-constrained devices.
How JPEG quality works
toDataURL('image/jpeg', 0.92) uses the browser canvas JPEG encoder. The quality value is normally between 0 and 1; higher values preserve more detail but create larger files. JPEG does not preserve transparency. If your element has transparent areas or needs lossless text and line art, use image/png instead:
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
const pngUrl = canvas.toDataURL('image/png');
JPEG is a raster image, not a print document. For selectable text, pagination or reliable paper dimensions, generate a PDF with a browser automation or PDF workflow instead.
What html2canvas can and cannot capture
According to the html2canvas project, the library runs in modern browsers and is not intended for Node.js. It reads DOM and CSS information and paints a new canvas; it does not take a native screenshot of the browser’s compositor. Unsupported or complex CSS can therefore differ from what the user sees.
- Capture a mounted DOM element, not a React component function or virtual DOM object.
- Only CSS understood by html2canvas is reproduced; filters, unusual blend modes, some pseudo-elements and browser-rendered effects may be absent or different.
- Cross-origin iframes cannot be read under browser security rules.
- Very large canvases can exceed browser- or platform-specific limits and result in blank, partial or failed output. There is no single safe maximum for every browser and device.
For visual-critical work, compare the export with the page at the target viewport. If fidelity is not acceptable, switch to a real-browser screenshot API.
Make assets ready before capture
Images and CORS
Remote images must be served with suitable CORS response headers. Setting useCORS: true asks html2canvas to request images with CORS; it does not bypass the browser’s content policy. If an image host does not grant access, the image may be omitted or the canvas may become unreadable when you call toDataURL. The html2canvas FAQ states plainly: “html2canvas cannot circumvent browser content policy restrictions.”
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Prefer same-origin assets or configure the image server with an appropriate Access-Control-Allow-Origin policy. A server-side proxy can fetch and serve approved assets from your own origin, but never create an unrestricted URL-fetch endpoint: validate allowed hosts, limit protocols, enforce size and timeout limits, and protect it from SSRF.
Fonts, lazy content and animations
Capture only after content is actually ready. Await critical fonts and images, render lazy sections, and pause animations or carousels so the frame is deterministic:
await document.fonts.ready;
await Promise.all(
Array.from(cardRef.current.querySelectorAll('img')).map((img) =>
img.complete
? Promise.resolve()
: new Promise((resolve) => {
img.addEventListener('load', resolve, { once: true });
img.addEventListener('error', resolve, { once: true });
})
)
);
Place this wait immediately before html2canvas. An image error is resolved deliberately so one broken optional image does not leave the export waiting forever.
Set a stable capture box
Give the export element an explicit width, background and spacing. Responsive wrapping can change when device pixel ratio or a narrow viewport changes. If you need a specific output size, temporarily apply a capture class with fixed dimensions, then remove it after the promise resolves.
Recommended Free Tools
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Download, upload or display the JPG
The data URL is suitable for a local download or preview:
const jpgDataUrl = canvas.toDataURL('image/jpeg', 0.9);
setPreview(jpgDataUrl);
For larger files or an upload endpoint, convert the canvas to a Blob rather than keeping a potentially huge base64 string:
canvas.toBlob(async (blob) => {
if (!blob) throw new Error('JPEG encoding failed');
const form = new FormData();
form.append('file', blob, 'card.jpg');
await fetch('/api/upload', { method: 'POST', body: form });
}, 'image/jpeg', 0.92);
Handle rejected promises and encoding errors in your UI. Disable the button during capture to prevent multiple expensive canvases from being created.
When Playwright or Puppeteer is the better choice
Use a real browser when you need the actual rendered page, full-page capture, server-side jobs, cross-origin pages you control through browser context settings, or CSS that html2canvas cannot reconstruct. Playwright’s screenshot API supports PNG, JPEG and WebP output; JPEG and WebP accept quality settings. A minimal server-side example is:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
import { chromium } from 'playwright';
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1200, height: 800 } });
await page.goto('https://example.com', { waitUntil: 'networkidle' });
await page.locator('#card').screenshot({ path: 'card.jpg', type: 'jpeg', quality: 92 });
await browser.close();
Browser automation requires installing and operating a browser, managing timeouts and sandboxing, and deciding how to handle authentication and untrusted URLs. Puppeteer is another documented direction for server-side screenshots. Choose based on your deployment and browser-support requirements; the available sources do not establish a universal performance winner.
Or skip the browser setup
ScreenshotNeo is a hosted screenshot API and MCP server. A single request captures a URL as PNG, JPEG, WebP or PDF. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status.
Use the API documentation at https://screenshotneo.com/docs/ for all options. The same endpoint supports element selectors, full-page lazy-image loading, dark mode, device presets or custom viewports, retina scale, PDF settings, custom CSS and JavaScript, clicks, waits, ad and tracker blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparency, resizing, chosen cache TTLs, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage data and an OpenAPI specification.
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)
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(`${res.status} ${res.statusText}`);
const data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));
ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients. Plans include 1,000 free shots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to get an API key.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Troubleshooting checklist
The JPG is blank or partly missing
- Wait for fonts, images and lazy content before capture.
- Check for a canvas-size limit; lower
scale, capture a smaller element or split a long page. - Inspect unsupported CSS and replace effects that html2canvas cannot reproduce.
“Tainted canvas” or a security error
- Identify cross-origin images and verify their CORS headers.
- Use same-origin hosting or a restricted, authenticated proxy.
- Do not expect
useCORSto override browser policy, and do not attempt to read cross-origin iframes.
Text or layout differs
- Ensure the intended webfont has finished loading with
document.fonts.ready. - Pause animations and fix the capture element’s width and background.
- Move to Playwright or Puppeteer when native browser fidelity is required.
The browser freezes or the download fails
- Lower device-pixel scale and JPEG quality, or use
toBlobto avoid a large base64 string. - Disable repeated clicks while a capture is running.
- For server workloads, queue jobs, set navigation and capture timeouts, and close browser instances in a
finallyblock.
Choosing the right method
| Requirement | Recommended approach | Main trade-off |
|---|---|---|
| Export a simple React component in the user’s browser | html2canvas | Easy setup, but reconstructed CSS may differ |
| Exact browser-rendered element or full page | Playwright screenshot | Browser automation and operational overhead |
| Server-side or scheduled captures | Playwright, Puppeteer or ScreenshotNeo | Requires browser operations or a hosted service |
| Selectable text and paginated output | PDF workflow | Not a JPG image |
Frequently Asked Questions
Can html2canvas capture an entire React page?
It can capture a chosen DOM element, including a container sized to page content, but very large canvases may exceed browser limits. For dependable full-page screenshots, use a real-browser workflow.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Does converting PNG to JPG improve transparency?
No. JPEG has no alpha channel. Transparent pixels need a chosen background color or a PNG output.
Can I run html2canvas in Node.js?
No. It is a browser-side library. Use Playwright, Puppeteer or a hosted screenshot API for Node.js generation.
Why is my external iframe missing?
Browser same-origin rules prevent html2canvas from reading cross-origin iframe content. Capture that page separately with browser automation or an API.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Quick 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.

