ScreenshotNeo

BlogHow-to

How to Capture Text as an Image With html2canvas

Render an HTML text block to a sharp PNG with html2canvas, handle fonts and cross-origin images, and troubleshoot blurry or missing content.

By the ScreenshotNeo team30 September 20267 min read

How to Capture Text as an Image With html2canvas

Direct answer: select the text element, wait for its fonts and images to finish loading, call html2canvas(element, options), then export the returned canvas with toDataURL() or toBlob(). html2canvas runs in a browser and reconstructs the element from the DOM and CSS; it is not a native browser screenshot.

1. Install html2canvas

Install the package from npm:

npm install @html2canvas/html2canvas

The official getting-started documentation covers installation and the Promise-based API: html2canvas documentation.

2. Minimal text-to-PNG example

This complete browser example captures a text block, displays the canvas, and downloads a PNG.

html2canvas traverses the DOM, renders a canvas, and then the Canvas API exports the image.
html2canvas traverses the DOM, renders a canvas, and then the Canvas API exports the image.
import html2canvas from '@html2canvas/html2canvas';

const element = document.querySelector('#text-to-capture');
if (!element) {
  throw new Error('Could not find #text-to-capture');
}

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

document.body.appendChild(canvas);

const link = document.createElement('a');
link.download = 'text.png';
link.href = canvas.toDataURL('image/png');
link.click();

html2canvas() resolves to a <canvas>. The download is a separate Canvas API operation. Use toBlob() instead when you need a Blob for uploading or other file handling.

3. A complete runnable page

Save this as an HTML entry point in a project using a JavaScript bundler that can import @html2canvas/html2canvas.

<main>
  <article id="text-to-capture" class="card">
    <h1>Release notes</h1>
    <p>The new export workflow preserves line breaks, emphasis, and links.</p>
    <p><strong>Tip:</strong> wait for fonts before capturing long text.</p>
  </article>
  <button id="download" type="button">Download PNG</button>
</main>

<script type="module">
  import html2canvas from '@html2canvas/html2canvas';

  const button = document.querySelector('#download');
  const element = document.querySelector('#text-to-capture');

  button.addEventListener('click', async () => {
    button.disabled = true;
    try {
      if (document.fonts?.ready) {
        await document.fonts.ready;
      }

      const canvas = await html2canvas(element, {
        backgroundColor: '#ffffff',
        scale: Math.min(window.devicePixelRatio || 1, 3),
        useCORS: true,
        onError(error) {
          console.error('html2canvas resource error:', error);
        },
      });

      canvas.toBlob((blob) => {
        if (!blob) throw new Error('Canvas could not be converted to a Blob');
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.download = 'release-notes.png';
        link.href = url;
        link.click();
        URL.revokeObjectURL(url);
      }, 'image/png');
    } finally {
      button.disabled = false;
    }
  });
</script>

4. Make text crisp and complete

Control output density with scale

scale determines the canvas pixel density. It defaults to window.devicePixelRatio. A higher value generally produces sharper text, but increases memory use, rendering time, and output size. Set it deliberately for predictable output:

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

For user-controlled pages, cap the value rather than multiplying an unusually large device pixel ratio.

Wait for fonts and images

Capture only after the page reaches its own ready state. A web font that is still loading can be replaced by fallback glyphs, changing line breaks and the final appearance.

await document.fonts?.ready;

await Promise.all(
  [...document.images]
    .filter((image) => !image.complete)
    .map((image) => new Promise((resolve) => {
      image.addEventListener('load', resolve, { once: true });
      image.addEventListener('error', resolve, { once: true });
    }))
);

This waits for resources already present in the document. It does not repair a server that blocks cross-origin access.

Choose the background

The default background is white. Set backgroundColor to a color for an opaque image or null for transparency:

const transparentCanvas = await html2canvas(element, {
  backgroundColor: null,
});

Capture a long or responsive text block

Use windowWidth and windowHeight to control layout and media queries. Use x, y, width, and height to crop a rectangle.

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

Very large canvases can hit browser canvas-size or memory limits. Split a long document into sections when a single capture fails or becomes slow.

Exclude controls and decoration

Add data-html2canvas-ignore to buttons, menus, or other elements that should not appear:

<button data-html2canvas-ignore>Download</button>

5. Cross-origin images, SVG, and iframes

html2canvas follows browser content-policy rules. An image from another origin can taint the canvas, making toDataURL() and similar export operations fail. Set useCORS: true only when the image server sends suitable CORS headers. Otherwise, serve the asset through a same-origin proxy configured with the proxy option. The project’s configuration documentation describes these options: configuration reference.

const canvas = await html2canvas(element, {
  useCORS: true,
  proxy: '/image-proxy',
});

allowTaint does not make a tainted canvas readable for export. Cross-origin iframes cannot be rendered because the browser does not expose their contentDocument; same-origin iframes can be traversed recursively.

6. Important options reference

Option Purpose Practical use
scale Output pixel density Increase for sharper text; watch memory.
backgroundColor Canvas background Use a color for opaque output or null for transparency.
x, y, width, height Capture rectangle Crop to a specific text region.
windowWidth, windowHeight Layout viewport Make responsive text wrap consistently.
scrollX, scrollY Scroll position Control captures involving fixed-position content.
useCORS Request images with CORS Use only when the image origin permits it.
proxy Proxy inaccessible resources Route images through a same-origin endpoint.
data-html2canvas-ignore Skip an element Hide controls or overlays from the output.
onError Observe resource failures Log missing images or SVG resources.

7. Why the result differs from a browser screenshot

html2canvas reconstructs a visual representation by traversing the DOM and reading CSS. Unsupported CSS, plugins, inaccessible external content, and browser security rules can therefore produce an image that differs from what the browser paints. It is designed for browser-side captures of pages or page regions, not for server-side rendering or pixel-perfect native screenshots.

8. Troubleshooting

Symptom Cause Fix
Text is blurry Canvas density is too low. Set scale to a deliberate value such as 2, then check memory use.
Text wraps differently Fonts were not ready or the viewport differs. Await document.fonts.ready and set windowWidth/windowHeight.
Images are missing The image failed to load or is blocked cross-origin. Wait for images, inspect onError, enable CORS on the image server, or use a same-origin proxy.
toDataURL() throws a security error A cross-origin resource tainted the canvas. Configure valid CORS headers or proxy the resource. Do not rely on allowTaint for export.
A long element is cut off The capture viewport or crop is smaller than the content. Use the element’s scroll dimensions for windowWidth, windowHeight, width, and height; split the capture if browser limits are reached.
A button or popup appears It is inside the selected element. Add data-html2canvas-ignore or capture a narrower element.
An iframe is blank It is cross-origin. Move content to the same origin or capture the iframe separately where permitted.
Nothing is captured The selector is wrong or the element is not visible. Check document.querySelector(), visibility, dimensions, and the capture viewport.

9. Performance, reliability, and cost

  • Capture the smallest element that satisfies the requirement. Smaller DOM trees and canvases use less memory.
  • Use the lowest scale that meets your output-quality requirement.
  • Wait for fonts and images once, then capture; repeated captures of the same large element multiply work.
  • Keep a fallback for Blob creation failures and very large canvases. Browser limits vary by device.
  • html2canvas runs in the user’s browser, so it has no server API charge, but it consumes the user’s CPU and memory and remains subject to browser security restrictions.
  • The official sources reviewed for this topic publish no benchmark figures. Treat render time and maximum canvas size as application-specific and measure them in your target browsers.

10. Or skip the browser setup

For a server-side screenshot, ScreenshotNeo accepts one GET request and returns a PNG, JPEG, WebP, or PDF. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server also lets Claude, Cursor, and other MCP clients take screenshots.

A server-side capture service can remove common consent banners and overlays before rendering.
A server-side capture service can remove common consent banners and overlays before rendering.

See the ScreenshotNeo API documentation for all options.

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(`Screenshot failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo includes 1,000 screenshots per month free with no card. Paid plans start at $5 for 3,000 screenshots, and every feature is available on every plan. Create a free ScreenshotNeo account.

11. FAQ

Can html2canvas run in Node.js?

No. It depends on browser APIs and is intended for modern evergreen browsers. Use a browser automation or screenshot API for server-side work.

Does html2canvas create a real screenshot?

No. It rebuilds the selected DOM and CSS into a canvas, so unsupported styles and inaccessible content can differ from native pixels.

Should I use toDataURL() or toBlob()?

Use toDataURL() for a simple download link. Use toBlob() for uploads and file pipelines.

Why does increasing scale eventually make things worse?

A larger canvas consumes more memory and can hit browser limits. Increase it gradually and split oversized captures.

Can html2canvas capture a cross-origin iframe?

No. The browser does not expose a cross-origin iframe’s document to the script.