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

html2canvas does not accept an HTML string directly. It accepts a DOM element. Put the string in a temporary, document-attached element, wait for fonts and images, then call await html2canvas(element, options). The Promise resolves to an HTMLCanvasElement that you can display, convert to a data URL, or export as a Blob.

The working pattern

Install or import html2canvas in your browser application, create a host element, assign the string to it, attach the host to document.body, and capture it. Attaching matters: a detached node has no normal document layout context, so computed styles, media queries, and resource resolution can be wrong or missing.

import html2canvas from '@html2canvas/html2canvas';

export async function renderHtmlString(html, options = {}) {
  const host = document.createElement('div');
  host.innerHTML = html;
  host.style.position = 'fixed';
  host.style.left = '-100000px';
  host.style.top = '0';
  host.style.width = 'fit-content';
  document.body.appendChild(host);

  try {
    return await html2canvas(host, {
      backgroundColor: null,
      ...options
    });
  } finally {
    host.remove();
  }
}

Use the function from a click handler, component action, or other browser-side code:

const html = `
  <article class="card">
    <h1>Invoice #1042</h1>
    <p>Total: <strong>$149.00</strong></p>
  </article>
`;

const canvas = await renderHtmlString(html, {
  backgroundColor: '#ffffff',
  scale: 2
});
document.querySelector('#preview').replaceChildren(canvas);

The library runs entirely in the browser; it is not a Node.js HTML renderer. The returned canvas is the result, not an image file by itself.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
ClearClick AV to HDMI Converter 3.0 (Third Generation) - 1080P RCA or S-Video to HDMI Upscaler - with Remote Control for Image Adjustment - VHS, VCR, Camcorder, DVD, TV, Gaming Systems, PAL, NTSC
  • AV To HDMI Converter 3.0 - Convert & Upscale RCA / S-Video / Analog Video Input to HDMI (TV or Monitor) at 1080P or 720P - Plug and Play Adapter with No Computer or Drivers Required
  • Upscaler Compatible with VCR, VHS, Camcorders, Hi8, Gaming Systems, Set-Top Boxes, DVD Players, & More. RCA/AV/Composite and S-Video Input. HDMI Output. Works with PAL and NTSC. (Important Note: Does NOT Downscale HDMI to RCA/AV/S-Video)
  • NEW! Remote Control Included - Fine Tune Your Video's Image Quality By Adjusting Brightness, Contrast, Saturation, Hue, Resolution (1080P or 720P), Aspect Ratio (Preserve Original 4:3 Look with Black Bars or Stretch To 16:9 HD Widescreen To Fill Your TV Screen)
  • NEW! S-Video Input - Allows S-Video Input From Camcorder, VCR, DVD Player, & More - Providing The Highest Possible Video Quality From These Sources (S-Video Cable Not Included - RCA/AV Cable Required For Audio Signal)
  • Includes 2-Year Warranty & Tech Support from ClearClick, a USA-Based Small Business (Extendable to 3 Years for Free - See User's Manual)

Turn the canvas into an image or upload

Data URL

const pngDataUrl = canvas.toDataURL('image/png');
const img = new Image();
img.src = pngDataUrl;
document.body.appendChild(img);

A data URL is convenient for a preview, but large captures consume memory. For downloads or uploads, a Blob is usually better.

Blob download

canvas.toBlob((blob) => {
  if (!blob) throw new Error('Canvas export failed');
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = 'capture.png';
  link.click();
  URL.revokeObjectURL(link.href);
}, 'image/png');

For JPEG, pass 'image/jpeg' and a quality value between 0 and 1. PNG preserves transparency and is the safer default for text and UI screenshots.

Safely handling the HTML string

innerHTML treats the string as markup. If any part comes from a user, database, URL, or other untrusted source, sanitize it before insertion with a maintained HTML sanitizer. html2canvas paints content; it is not an HTML sanitizer and should not be used as a security boundary.

For a complete document string containing <html>, <head>, or <body>, parse with DOMParser, then copy the intended body content into the temporary host. A fragment is simpler when you control the template:

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.
const parsed = new DOMParser().parseFromString(html, 'text/html');
const host = document.createElement('div');
host.append(...parsed.body.childNodes);
document.body.appendChild(host);

Do not assume styles from the parsed document’s detached <head> will automatically apply. Load the stylesheet in the live page or copy the required styles into the live document.

Make fonts, images, and layout ready before capture

Fonts

Web fonts can still be loading when the capture starts. Wait for the browser’s font set:

Rank #2
GINGIN AV to HDMI Converter, AV to HDMI Adapter Support 720p/1080p for PS1/PS2/PS3/Xbox 360/WII/N64/SNES/STB/VHS/VCR/Blue-Ray DVD Players
  • Composite to HDMI Converter: Converts analog AV composite (Yellow, White, Red) input to HDMI 720P/1080P (60HZ) output, displayed on smart TV, Projector or HD Display, which bring back your old and cherish memories.
  • Plug to Play: This HDMI Converter no extra drivers need, just plug and play,easy to use. Please hook up the USB Power Cable (included) to 5V power source during use. Note: The Video Converters only support converts AV to HDMI, can't converts HDMI to AV.
  • Widely Used: This composite to hdmi adapter is widely applied to PS1, PS2, PS3, Xbox, N64, Wii, STB, VHS, VCR, DVD Players and other devices with standard composite AV input. Note: It can only be used when PS2 is set to RGB output.
  • Wide Compatibility: This Video Audio Converter Adapter supports source formats of PAL, NTSC3.58, NTSC4.43, SECAM, PAL/M, PAL/N standard TV. Provide advanced signal processing with great precision, colors, resolutions, and details. Important Note: This converter can't improve video quality!
  • Attention & Package: Please ensure to connect this av hdmi converter to power source to make it work. Package include: 1*AV to HDMI Adaptor, 1*USB Power Cable(adapter not included), 1*User Manual.
await document.fonts.ready;
const canvas = await renderHtmlString(html, options);

If a font fails to load, the browser may substitute another face. Verify the font request and compare output in the browser you will use for capture.

Images and cross-origin rules

Remote images must be reachable and permitted by browser security policy. Set useCORS: true only when the image server returns an appropriate Access-Control-Allow-Origin header:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const canvas = await renderHtmlString(html, {
  useCORS: true
});

If you cannot change the image server, use a same-origin proxy that retrieves the image and serves it from your origin. The browser’s policy cannot be bypassed by html2canvas. allowTaint defaults to false; enabling it does not grant cross-origin access and can leave the canvas unreadable for export.

Wait for image elements when the string includes images:

const host = document.createElement('div');
host.innerHTML = html;
document.body.appendChild(host);
await Promise.all([...host.querySelectorAll('img')].map((img) => {
  if (img.complete) return Promise.resolve();
  return new Promise((resolve) => {
    img.addEventListener('load', resolve, { once: true });
    img.addEventListener('error', resolve, { once: true });
  });
}));

Integrate that wait into your temporary-host helper if image timing is important. An error event prevents a broken image from blocking forever, while still leaving you to decide whether a missing image should fail the operation.

Options that control the result

Option Use Important behavior
backgroundColor Set the canvas background null preserves transparency. When no DOM background is present, the documented default is white.
scale Control pixel density Defaults to the device pixel ratio. Higher values sharpen output but increase memory and processing time.
width, height Set capture dimensions Use them to constrain the rendered area.
x, y Crop the capture Offsets define where capture begins within the element.
windowWidth, windowHeight Control layout viewport values Useful when media queries or long-page layout depend on viewport dimensions.
useCORS Attempt CORS image loading Works only when the server supplies the required CORS header.
proxy Retrieve remote resources through a proxy The proxy must be available to your application and return usable responses.
foreignObjectRendering Ask the browser to render through SVG foreignObject where supported It can help with some markup, but does not guarantee complete CSS fidelity.
ignoreElements Exclude nodes programmatically Provide a predicate that returns true for nodes to omit.
data-html2canvas-ignore Exclude marked nodes Add the attribute to an element you do not want painted.

For example, this excludes a close button, preserves transparency, and captures at two-times density:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
RuiPuo RCA to HDMI Converter, AV to HDMI Adapter Support 1080P, PAL/NTSC Compatible with WII/WII U/PS one/PS2/PS3/STB/Xbox/VHS/VCR/Blue-Ray DVD ect.
  • Input: RCA, Output: HDMI; Converts Analog Composite Input to HDMI 1080p or 720p Output.
  • RCA to HDMI Converter - Plug and Play, Easy to Install and Operate, Powered by External USB Cable.
  • RCA to HDMI Converter supports connecting HDMI capture card (note that we do not include HDMI capture card).
  • Composite to HDMI Converter Widely Applied to PS One, PS2, PS3, N64, WII, WII U, STB, VHS, VCR, Blue-Ray DVD Players Projector (Note: It can only be used when PS2 is set to RGB output).
  • AV to HDMI Converter Support PAL, NTSC3.58, NTSC4.43, SECAM, PAL/M, PAL/N tv format.
const canvas = await renderHtmlString(html, {
  backgroundColor: null,
  scale: 2,
  ignoreElements: (element) => element.matches('.close-button')
});

Long pages, cropping, and browser limits

A blank or partially captured result can mean that the requested bitmap exceeds the browser’s canvas-size limits. Large dimensions also multiply memory use: increasing both page size and scale can become expensive quickly.

For long content, measure the relevant scroll dimensions and provide viewport values that match the layout:

const canvas = await renderHtmlString(html, {
  windowWidth: host.scrollWidth,
  windowHeight: host.scrollHeight,
  width: host.scrollWidth,
  height: host.scrollHeight
});

If the page is still too large, capture sections separately and combine the resulting images, or reduce scale. Use x, y, width, and height for deliberate crops instead of relying on accidental viewport clipping.

Why CSS does not always match the browser

html2canvas reconstructs the picture rather than asking the browser for a native screenshot. Its project documentation notes that every CSS property must be implemented manually, so full CSS support is not promised. Advanced effects, unusual filters, complex blending, and browser-specific rendering can differ.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Reduce unsupported or unusually complex CSS in the capture template.
  • Use foreignObjectRendering as an experiment where your target browser supports it, not as a fidelity guarantee.
  • Wait for fonts and images before comparing output.
  • Test in the same browser engine and viewport used in production.

This distinction also explains why an html2canvas image is not necessarily identical to a screenshot made by browser automation.

Common failures and fixes

Nothing renders from the string

Cause: the host is detached or has no measurable layout. Fix: append it to a live document before calling html2canvas, and inspect its dimensions before capture.

Rank #4
ABLEWE RCA to HDMI,AV to HDMI Converter, 1080P Mini RCA Composite CVBS Video Audio Converter Adapter Supporting PAL/NTSC for TV/PC/ PS3/ STB/Xbox VHS/VCR/Blue-Ray DVD Players
  • RCA to HDMI Converter: Converts analog RCA composite (Yellow, White, Red) input to HDMI 720P/1080P (60HZ) output,displayed on HDTV/Monitor,which can bring back your childhood memories.
  • Plug to Play: ABLEWE Mini RCA to HDMI converter no extra drivers need, just plug and play,easy to use.Please hook up the USB power cable (included) to 5V power source during use.
  • Wide Compatibility: Support source formats of PAL, NTSC3.58, NTSC4.43, SECAM, PAL/M, PAL/N standard TV. Provide advanced signal processing with great precision, colors, resolutions, and details.
  • Widely Used:Widely applied to PS2,PS3,Xbox,N64, WII, STB, VHS, VCR, DVD Players and other devices with standard composite AV input.
  • Attention & Package:Please ensure to connect this rca to hdmi converter to power source to make it work.Package include:1*RCA to HDMI Converter,1*usb power cable(adapter not included),1*User Manual.

The canvas is blank or cut off

Cause: incorrect viewport or element dimensions, or a browser canvas-size limit. Fix: set appropriate windowWidth/windowHeight, inspect scrollWidth and scrollHeight, reduce scale, or capture in sections.

Images are missing

Cause: the image has not loaded, the URL failed, or the origin does not permit CORS. Fix: wait for image load, verify the URL, set useCORS: true only with a matching server header, or use a same-origin proxy.

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

The exported canvas is security-tainted

Cause: a cross-origin resource was painted without successful CORS authorization. Fix: serve the asset with the correct CORS header or proxy it; changing allowTaint does not defeat browser security.

Fonts or advanced CSS look different

Cause: fonts were not ready or a CSS feature is not implemented by html2canvas. Fix: await document.fonts.ready, simplify the template, and test in the target browser.

The temporary content affects the visible page

Cause: the host participates in layout or has visible styling. Fix: position it off-screen as in the helper, give it an intentional width, and always remove it in a finally block.

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

Performance and reliability practices

  • Keep the capture subtree small; omit navigation, animations, and controls that are not part of the image.
  • Pause animations or use deterministic styles so repeated captures do not differ.
  • Choose the lowest scale that meets your output requirement.
  • Wait for network-dependent assets explicitly instead of relying on timing guesses.
  • Handle rejected Promises and export failures, and remove the temporary host even when capture fails.
  • Remember that this is browser-side work: the user’s device, browser limits, and security policy affect the result.

Or skip the browser setup

If you need a URL rendered without building a temporary DOM, ScreenshotNeo is a website screenshot API and MCP server. It accepts a URL and returns 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. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers.

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

One request is enough:

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 all parameters. The equivalent Python request is:

Best Value
BD&M RCA to HDMI Converter, AV to HDMI Adapter Supports PAL/NTSC for PS2, PS3, Xbox, VHS, VCR, DVD Players
  • Convert RCA to HDMI Instantly – BD&M RCA to HDMI Converter easily converts analog RCA/composite AV signals to HDMI output, allowing you to connect older devices to modern HDTVs, monitors, and projectors with clear video and audio quality.
  • Wide Device Compatibility – Supports VHS players, VCRs, DVD players, camcorders, retro gaming consoles, and more including PS1, PS2, PS3, Xbox, N64, Wii, and older AV devices with standard RCA output.
  • 1080P HDMI Output – Advanced signal processing delivers stable and sharp video output with support for 720P/1080P HDMI resolution, improving compatibility with modern TVs and displays.
  • Plug & Play Setup – No drivers or software required. Simply connect the RCA cables, HDMI cable, and included USB power cable for quick and easy installation in minutes.
  • Compact & Reliable Design – Lightweight mini converter design makes it perfect for home entertainment setups, retro gaming, travel, or converting old media collections while maintaining stable performance.
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)

And 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 also provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. Features include full-page captures with lazy images loaded, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, easing migration.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Sign up free for ScreenshotNeo.

When to choose html2canvas

Use html2canvas when the source is already in your browser, you need a client-side canvas, and you can control the DOM, assets, and security headers. Choose a URL screenshot service when you need repeatable rendering of remote pages, server-side automation, PDF output, or an AI agent workflow without creating the page in your own document.

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

Frequently Asked Questions

Does html2canvas accept a complete HTML document string?

Not as its first argument. Parse the document, move the intended content into an element attached to the live page, and pass that DOM element to html2canvas.

Can html2canvas run in Node.js?

The library runs in the browser and depends on a live Window and document. Use a browser-capable renderer for Node-based automation instead.

Why is my output different from a native screenshot?

html2canvas reimplements CSS painting, so unsupported properties, fonts, browser differences, and cross-origin resources can change the result.

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.

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.