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

To save a browser page’s <div> as an image, render that element into a canvas with a DOM-to-image library, then download the canvas as PNG. The example below uses html2canvas. This is a browser-side reconstruction of the element—not a pixel-perfect screenshot—and cross-origin images or unsupported CSS can affect the result.

What happens when you export a div

A <div> is HTML, not an image file. JavaScript first selects the element, a library renders its DOM and styles into a canvas, and the canvas is encoded as an image. The resulting file contains pixels, not editable HTML or CSS.

html2canvas returns a Promise that resolves to a canvas. You can turn that canvas into a PNG data URL and trigger a download. The library reconstructs the page from DOM and style information; it does not capture the browser’s native pixels. Its own compatibility and feature documentation should be checked against the CSS and browsers you intend to support.

Save a div as a PNG with html2canvas

Install the library

For an application using a JavaScript bundler, install the package from your project directory:

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
npm install html2canvas

Add a capture target and button

This example uses a real element with the ID capture. Include whatever content you want in the image inside that element. The button calls the export function when clicked.

<div id="capture">
  <h2>Quarterly update</h2>
  <p>This content will be saved as an image.</p>
</div>
<button id="save-image" type="button">Save as PNG</button>

Render and download it

Put this in a JavaScript module loaded by your page or application. The function checks that the target exists, waits for the render Promise, and downloads a PNG.

import html2canvas from 'html2canvas';

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

  const canvas = await html2canvas(element);
  const link = document.createElement('a');
  link.download = 'capture.png';
  link.href = canvas.toDataURL('image/png');
  link.click();
}

document.querySelector('#save-image')?.addEventListener('click', () => {
  saveDivAsPng().catch((error) => {
    console.error('Could not save the image:', error);
  });
});

Start the download from the user’s button click, as in this example. Keep the capture target in the document and visible while rendering. If your page does not use a bundler, use the browser setup documented by html2canvas and make sure the library is loaded before calling it; its getting-started guide describes both npm and browser use. html2canvas relies on browser APIs and is not suitable for Node.js by itself.

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

Choose a data URL or a Blob

Data URL for a direct download

canvas.toDataURL('image/png') encodes the image into a string that can be assigned to a link’s href. It is convenient for a small, direct download. For large captures, a data URL can require more memory than a Blob-based flow because it represents the image as encoded text.

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

Blob for downloads or uploads

canvas.toBlob() produces a Blob that can be used with an object URL. PNG encoding is required by the browser API; JPEG and WebP support depends on the browser. This example keeps the URL alive until the link is clicked, then revokes it after a short delay rather than invalidating it immediately.

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

  const canvas = await html2canvas(element);
  const blob = await new Promise((resolve) => {
    canvas.toBlob(resolve, 'image/png');
  });
  if (!blob) throw new Error('The browser could not create a PNG');

  const objectUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = objectUrl;
  link.download = 'capture.png';
  link.click();
  window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
}

If you use the Blob for an upload or display it elsewhere, keep the object URL valid for as long as that use requires. Release it when it is no longer needed. The delay above is a practical download example, not a guarantee for every browser or download workflow.

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.

Pick a format that matches the output

  • PNG: use for a straightforward lossless image export. It is the safest choice when the browser must support the encoding.
  • JPEG: can be useful for photographic content, but browser support for canvas encoding varies. The format does not preserve transparency.
  • WebP: may offer a smaller image, but browser encoding support varies as well. Check the returned Blob or output in the browsers you support rather than assuming the requested type was produced.

Changing the filename extension alone does not convert an image. Ask the canvas to encode the format you want, then verify the browser supports it and that the result is usable.

When the output does not match the page

CSS is reconstructed, not captured as browser pixels

html2canvas interprets the DOM and style information it can access. Unsupported CSS properties or rendering behaviors may look different in the exported image than they do on screen. Consult the project’s supported-features documentation for properties that matter to your design, then compare the actual output in each target browser.

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

Remote images and canvas security

A remote image may not be readable by the canvas unless its server grants suitable cross-origin access. If an image taints the canvas, the browser blocks reading or exporting its pixels. html2canvas has useCORS and proxy options, but they work only when the remote server and proxy conditions permit access; they do not bypass browser security policy. Check the image server’s CORS response and the library’s documentation before changing capture options.

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

Iframes have origin boundaries

Same-origin iframe support is documented by html2canvas, but a page cannot freely inspect a cross-origin iframe’s contents. If the div contains an iframe from another origin, the embedded content may be inaccessible to the renderer because of browser restrictions. You cannot solve that by selecting the iframe element from the parent page.

Compare the DOM-to-image approaches

Approach Useful distinction Check before using
html2canvas with toDataURL() Direct PNG download flow from a rendered canvas. DOM/CSS fidelity and access to images or other resources.
html2canvas with toBlob() Blob output works for object-URL downloads and upload workflows. Object URL lifetime and browser support for formats other than PNG.
html-to-image Another DOM-node conversion approach using canvas and SVG. Current project documentation and the exact page and browsers.
dom-to-image Uses SVG foreignObject containing HTML and rasterizes through canvas. foreignObject behavior and resource embedding in target browsers.

There is no universal winner established for every page. Compare the CSS your element uses, remote images and fonts, target browsers, desired output dimensions and whether the next step needs a Blob or data URL. Treat each library’s own documentation as guidance, not a guarantee that every layout will render identically.

Troubleshoot common export failures

  • The function says “Capture element not found.” The selector does not match an element at call time. Check the ID or selector spelling, and call the function after the page has created the element.
  • Remote images are missing or export fails with a security error. Check whether the image is cross-origin and whether its server grants CORS access. Configure the library’s documented CORS or proxy option only where the server and proxy permit it; browser policy still applies.
  • An iframe’s content is absent. Confirm whether it is same-origin. Cross-origin iframe content is not freely accessible to the parent page.
  • The exported design differs from the visible page. Check the library’s supported CSS features for the styles involved and test the exact element in the browser you need to support. html2canvas reconstructs rather than taking a native screenshot.
  • The Blob download is empty or unavailable. Check whether toBlob() returned null, as in the example, and handle that error instead of making an object URL from a missing Blob.
  • An image link stops working. Do not revoke its object URL immediately. Keep it alive while the image is displayed or used, then call URL.revokeObjectURL() when finished.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If what you need is a screenshot of a publicly reachable website by URL—not an export of a div already rendered in your own page—ScreenshotNeo provides a screenshot API and MCP server. It cannot capture an arbitrary local DOM element that you have not made available as a page URL; the browser method above is the right fit for that job.

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.

One GET request can return a PNG, JPEG, WebP or PDF. For example, this cURL request saves a PNG response for a webpage:

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 API documentation for authentication and request options. Cookie and consent banners are accepted before capture, and more than 60 known consent platforms, newsletter popups and chat widgets can be removed; each cleanup step can be turned off. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and response headers report the page verdict and billing status. An MCP server exposes take_screenshot, get_page_info and capture_pdf for AI agents and MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000, and every feature is on every plan.

Sign up free for 1,000 screenshots a month—no card required.

Frequently Asked Questions

Can I save a div as a JPG instead of a PNG?

Yes, if the browser supports JPEG canvas encoding. Request the JPEG MIME type and verify the resulting output; support for formats other than PNG varies.

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

Can html2canvas run in Node.js?

Not on its own: the project’s getting-started guidance says it depends on browser APIs and is not suitable for Node.js.

Will html2canvas capture content inside a cross-origin iframe?

No; browser same-origin restrictions prevent the parent page from freely accessing cross-origin iframe contents.

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.