DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober 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
HTML

Convert an HTML Element to JPG in the Browser (with html2canvas and html-to-image)

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

To convert one HTML element to a JPG, select the DOM node, render it to a canvas, then serialize that canvas as image/jpeg. In a browser, html2canvas plus canvas.toBlob() gives you control over quality, dimensions and downloading; html-to-image offers a shorter toJpeg() helper. Both reconstruct the element from DOM and style data, so the result is not guaranteed to match every pixel of the browser’s native rendering.

Choose the right conversion method

The best method depends on where your code runs and how exact the pixels must be.

Method How it works Best fit Important limitation
html2canvas + toBlob() Builds a canvas representation of a selected DOM node, then exports JPEG. Browser-side tools that need a Blob, download, upload, scaling or cropping. Only CSS and resources the library can read are reproduced; it is not a native screenshot.
html-to-image toJpeg() Provides a direct helper that returns a JPEG data URL. Small browser utilities where a data URL and download link are convenient. It has the same practical concerns around CSS support and cross-origin content.
Real browser screenshot service Loads the page in a browser engine and captures the rendered result. Server workflows, automated jobs, or cases where DOM reconstruction is insufficient. Requires a browser service or setup rather than a few client-side calls.

Neither library is a Node.js rendering solution by itself. If the conversion must run on a server, use a real browser-based capture workflow or an API.

Convert an element with html2canvas

1. Add html2canvas and mark the target

Install the package with your normal JavaScript package manager, or load the browser build in your page. Give the element a stable selector and make sure its content is in the DOM before capture:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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
<section id="capture" class="card">
  <h1>Monthly report</h1>
  <p>Revenue increased 18%.</p>
</section>
<button id="save-jpg">Save JPG</button>

2. Render the node and export JPEG

This complete browser example waits for the click, renders #capture, requests JPEG at quality 0.95, creates a temporary object URL and starts a download:

import html2canvas from 'html2canvas';

const button = document.querySelector('#save-jpg');
const element = document.querySelector('#capture');

button.addEventListener('click', async () => {
  button.disabled = true;
  try {
    const canvas = await html2canvas(element);

    canvas.toBlob((blob) => {
      if (!blob) {
        throw new Error('The browser could not encode a JPEG.');
      }
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.download = 'monthly-report.jpg';
      link.href = url;
      link.click();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
    }, 'image/jpeg', 0.95);
  } catch (error) {
    console.error('Element capture failed', error);
  } finally {
    button.disabled = false;
  }
});

toBlob() is asynchronous. If the requested type is unsupported, browser canvas serialization can fall back to PNG, so inspect the returned Blob type when the exact format matters.

Control resolution, scale and crop

Pass capture options when the default CSS-pixel output is too small or when only part of the node is needed:

const canvas = await html2canvas(element, {
  scale: 2,
  x: 0,
  y: 0,
  width: element.scrollWidth,
  height: element.scrollHeight
});

A larger scale increases pixel dimensions and memory use; it does not add detail that was absent from the source. For a full element with overflowing content, measure the element and its scroll dimensions, then test on the browsers and devices you support.

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

Upload instead of downloading

The Blob can be sent directly to your server without creating a data URL:

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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
canvas.toBlob(async (blob) => {
  if (!blob) return;
  const form = new FormData();
  form.append('file', blob, 'element.jpg');
  await fetch('/upload', { method: 'POST', body: form });
}, 'image/jpeg', 0.9);

Use html-to-image’s direct JPEG helper

When a data URL is suitable, html-to-image documents toJpeg(node, { quality }) and a download-link pattern:

import { toJpeg } from 'html-to-image';

const node = document.querySelector('#capture');
const dataUrl = await toJpeg(node, { quality: 0.95 });
const link = document.createElement('a');
link.download = 'monthly-report.jpg';
link.href = dataUrl;
link.click();

This is concise, but data URLs keep the encoded image in a string and can be less convenient for large files or uploads. Prefer the html2canvas Blob path when you need streaming-style upload handling or explicit MIME-type checks.

Make the output match the element

Wait until content is ready

Capture after fonts, images and asynchronous data have loaded. If an image is still loading, the canvas may contain an empty area. A practical pattern is to await known images before calling the renderer:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await Promise.all([...document.images].map((img) => {
  if (img.complete) return Promise.resolve();
  return new Promise((resolve) => {
    img.addEventListener('load', resolve, { once: true });
    img.addEventListener('error', resolve, { once: true });
  });
}));

Freeze animations and hover states if deterministic output matters. Apply a capture-only class that sets animation: none, hides controls, and uses a fixed width.

Account for CSS support

DOM-to-image libraries implement only portions of the browser’s CSS and layout behavior. Verify gradients, filters, pseudo-elements, web fonts, blend modes, transforms and generated content in the browsers you ship. A visually correct live page is not proof that the reconstructed canvas will be identical.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.

Handle transparency and JPEG’s background

JPEG does not preserve transparency. If your element has transparent pixels, place it on an explicit background before capture, or choose PNG when transparency is required:

const canvas = await html2canvas(element, {
  backgroundColor: '#ffffff'
});

Cross-origin images and iframes

Browser security rules are the most common reason an otherwise correct script fails. Images hosted on another origin need appropriate cross-origin access headers and a configuration that allows the renderer to fetch them. A library cannot override the browser’s same-origin policy. If a cross-origin image taints the canvas, reading or exporting it can be blocked.

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

Cross-origin iframes are stricter: their document is not accessible to page JavaScript, so a DOM-to-canvas library cannot render their contents. Proxy permitted assets through your own origin, configure the image host for cross-origin use, or capture the complete page with a browser screenshot service that loads it as a user agent.

Large elements, cropping and blank output

Canvas dimensions have browser- and platform-dependent limits. There is no universal maximum that is safe for every device. Very large nodes can produce blank or partially rendered output, especially when their scroll dimensions are much larger than the viewport.

  • Capture a smaller region or split a long document into multiple images.
  • Reduce scale before increasing it again.
  • Set capture dimensions from the element’s actual scroll width and height rather than arbitrary page dimensions.
  • Test on low-memory mobile devices as well as desktop browsers.

For full-element cases, matching the renderer’s window width and height to the element’s scroll dimensions can help, but it does not remove underlying canvas limits.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting checklist

The file downloads but is PNG

Check the Blob’s type. Canvas serialization falls back to PNG when the requested format is unsupported. Confirm that the browser accepts image/jpeg and that your code does not replace the Blob with a data URL generated by another step.

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

Images are missing or export throws a security error

Inspect every image URL, including CSS backgrounds. Serve assets from the same origin or configure the asset server for cross-origin access. A proxy can relay permitted images through your origin; it cannot grant access to content you are not authorized to retrieve.

An iframe is blank

A cross-origin iframe cannot be traversed by page JavaScript. Capture content you control in the parent document, use a cooperative message-based integration, or switch to a browser capture service.

The result differs from what I see

That is expected when unsupported CSS, web-font timing, animations or pseudo-elements are involved. Disable motion, await fonts and images, simplify capture-only styles, and compare the output in each supported browser. For pixel-faithful capture, use a real browser screenshot rather than DOM reconstruction.

The output is blank or incomplete

Reduce the node’s dimensions or scale, capture in tiles, and check for browser canvas-size limits. Ensure the element is attached, visible and has non-zero dimensions at capture time.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.

It works in the browser but not in Node.js

html2canvas depends on browser APIs and is documented as browser-only. Run the code in a browser, or use an automated real-browser service for server-side jobs.

Performance, quality and format decisions

  • Quality: JPEG quality around 0.95 is a useful high-quality starting point. Lower values reduce transfer size with more visible compression.
  • Memory: Pixel count grows with both element dimensions and scale. Release object URLs with URL.revokeObjectURL() after use.
  • Repeat captures: Reuse the selected node, avoid unnecessary full-page dimensions, and debounce capture buttons so multiple canvases are not created at once.
  • Text and transparency: JPEG is appropriate for photographic or opaque cards. PNG is usually better for sharp text, line art or transparent backgrounds.
  • Exactness: DOM reconstruction is convenient but not equivalent to capturing the compositor’s final pixels.

Or skip the browser setup

ScreenshotNeo is a browser screenshot API and MCP server for developers. It loads a URL in a real browser and returns PNG, JPEG, WebP or PDF; for an element workflow, add the service’s selector and capture options to your request. A one-call JPEG example is:

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 response formats and options. You can also call it from 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)

Or from 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 banners, newsletter popups and chat widgets are removed before the shot; each cleanup step can be disabled.
  • Bot checks, 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. Every feature is available on every plan.

Create a free ScreenshotNeo account to try the API without a card.

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.

When to use each approach

  • Use html2canvas when the element is already in your browser page, assets are same-origin or configured for access, and a reconstructed canvas is acceptable.
  • Use html-to-image when you want a compact data-URL workflow and have verified the target CSS.
  • Use ScreenshotNeo or another real-browser capture path when the work is server-side, pages contain third-party frames, or the final rendered pixels matter more than client-side simplicity.

Frequently Asked Questions

Can I convert an element without downloading it?

Yes. With html2canvas, pass the Blob from canvas.toBlob() to fetch() or FormData; html-to-image can return a data URL for storage or upload.

Does JPEG keep transparent backgrounds?

No. JPEG has no alpha channel. Set an opaque background before capture or export PNG instead.

Why can’t a DOM library capture a third-party iframe?

The browser prevents page JavaScript from reading a cross-origin iframe document, so the library cannot traverse or render its contents.

Is html2canvas suitable for a backend job?

Not directly. It depends on browser APIs. Run it in a browser or use a real-browser screenshot service for backend automation.

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.

Leave a Reply

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

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.

Read next

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.