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

Install html2canvas, get a reference to the Angular element you want to render, and call html2canvas(element) in the browser after Angular has rendered it. The returned Promise resolves to a canvas you can display or export. It reconstructs an image from the DOM and supported CSS; it is not a pixel-for-pixel capture of the browser window, so check its CSS and cross-origin limitations before relying on the output.

Install html2canvas and identify the element

Install the package from your project directory:

npm install html2canvas

Import the default export from html2canvas. Give the component section you want to capture a template reference, then obtain its DOM element through Angular’s view-query API. This example uses signal-based viewChild syntax; adapt the query syntax to your Angular version if necessary.

import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
import html2canvas from 'html2canvas';

@Component({
  selector: 'app-report',
  standalone: true,
  template: `
    <section #capture class="report">
      <h2>Monthly report</h2>
      <p>This is the area that will be rendered.</p>
    </section>
    <button type="button" (click)="saveImage()">Save image</button>
  `
})
export class ReportComponent {
  readonly capture = viewChild.required<ElementRef<HTMLElement>>('capture');
  private browserReady = false;

  constructor() {
    afterNextRender(() => {
      this.browserReady = true;
    });
  }

  async saveImage(): Promise<void> {
    if (!this.browserReady) return;

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

The essential operation is await html2canvas(element). The sample turns the resulting canvas into a PNG download. For an application that displays the result instead, append the canvas or set an image’s src from canvas.toDataURL(). Handle rejected Promises in production code so an image-loading or rendering failure does not become an unhandled error.

Run the capture at the right point in Angular’s lifecycle

Angular recommends render callbacks for manual DOM work. In the example, afterNextRender establishes that the initial browser render has completed before the capture button can be used. Call capture in response to a user action or another event that happens after the target content is ready; do not run it while Angular is still constructing the view. See Angular’s DOM APIs guidance and afterNextRender API.

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

ElementRef.nativeElement is the bridge to the underlying DOM node, but Angular describes direct DOM access as a last resort. Use it here because html2canvas requires a real element. Keep DOM-dependent code narrowly scoped and avoid direct access when Angular template bindings can do the job.

Server-side rendering and hydration

afterNextRender runs on browser platforms, not during server-side rendering or build-time prerendering. Keep the html2canvas call and browser APIs such as document and HTMLCanvasElement out of server-evaluated paths. Angular also notes that a component is not guaranteed to be hydrated when the render callback runs. If your app uses hydration, make sure the target has actually become interactive and is ready before enabling capture; the callback alone is not a hydration-completion guarantee.

Choose options for the output you need

The basic call uses defaults. Pass a second options object when the target needs a particular background, scale, viewport, crop, or resource-loading behavior. The following options are documented by html2canvas; their suitability depends on the page and browser.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
Option What it controls Practical note
backgroundColor Canvas background color Set a solid color if a transparent-looking or unexpected background is undesirable.
scale Output pixel density Documented default is window.devicePixelRatio. A higher scale creates more pixels and can increase memory use.
useCORS Attempts CORS loading for images Documented default is false. It does not override the remote server’s CORS policy.
proxy Proxy URL used for resource loading Use only a proxy you control or trust and configure for the needed resources.
onclone Callback to adjust the cloned document before rendering Useful for capture-only styling or state changes without altering the live page.
ignoreElements Predicate for excluding nodes Return true for elements that should not appear in the capture.
imageTimeout How long image loading is allowed to take Documented default is 15000 milliseconds; this is not a guarantee that every image will load.
width, height Output dimensions Set deliberately when the default element bounds are not the desired output size.
x, y Crop origin Use with dimensions to capture a particular region.
scrollX, scrollY Scroll position used for rendering Relevant when positioning or page scroll affects the target.
windowWidth, windowHeight Virtual window dimensions Can help when rendering content whose layout or scrollable area differs from the visible viewport.

The configuration reference lists these options and defaults at html2canvas configuration. A target element can also opt out by including data-html2canvas-ignore. For full-page or scrollable content, test how the target’s scroll dimensions and virtual window dimensions interact rather than assuming that a larger canvas automatically contains every off-screen item.

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

Example with explicit settings

const canvas = await html2canvas(element, {
  backgroundColor: '#ffffff',
  scale: 2,
  useCORS: true,
  imageTimeout: 15000,
  windowWidth: element.scrollWidth,
  windowHeight: element.scrollHeight
});

This is a starting point, not a universal recipe. A higher scale can create a sharper image but a much larger canvas. Set window dimensions to suit the content and test in the browsers and devices your users rely on.

Know what html2canvas can and cannot render

The html2canvas documentation describes its approach as taking “screenshots” of webpages or parts of them directly in the user’s browser. In practice, it traverses the DOM and builds a representation using the CSS and elements it supports; it does not read the browser’s final composited pixels. The feature list documents support property by property and marks some features unsupported or limited.

Examples currently listed as unsupported include box-shadow, filter, mix-blend-mode, and object-fit; transforms are listed as limited. If a key effect disappears, simplify or restyle the capture target, or choose a capture method that produces a browser-level image when one is available in your runtime. Do not promise pixel-perfect output without verifying the actual template and assets in target browsers.

Handle external images and canvas security

Images from another origin may be blocked from the canvas unless the image server permits cross-origin access. The browser’s content policy still applies: useCORS: true only attempts CORS loading, and the remote server must send suitable headers. A configured proxy is another option when you can safely fetch and serve the required assets through it.

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.

Setting allowTaint does not make a tainted canvas readable. The html2canvas FAQ explains that cross-origin content can taint a canvas; once tainted, operations such as reading pixels or exporting with toDataURL() can fail. Consult the project’s FAQ and check the image host’s CORS response before changing application code.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Troubleshoot common capture problems

Images are missing

  • Check whether the images are served from the same origin as the app or from a different host.
  • For cross-origin images, confirm the image server sends CORS headers that permit the app’s origin; then try useCORS: true.
  • If you have a suitable server-side route, configure proxy and verify that it can retrieve the image. Do not expose an unrestricted proxy that can fetch arbitrary URLs.
  • Check that the image has loaded before capture and review the configured imageTimeout.

The canvas is empty or cuts off content

  • Confirm the selected reference points to the intended rendered element and that the capture runs after its content is ready.
  • Try a smaller target or region. Browser canvas size limits vary by browser, operating system, and hardware, so there is no single safe maximum size to apply everywhere.
  • For scrollable content, inspect scrollWidth and scrollHeight and set windowWidth or windowHeight appropriately.
  • Reduce scale if the output is too large for the device to render reliably.

A CSS property or visual effect is absent

Check the supported-features list for that property. If it is unsupported or limited, use a simpler capture-specific style—potentially applied in onclone—or use a browser-level capture facility when your environment provides one.

Capture fails in SSR or during startup

Keep the call inside browser-only execution and after the target view exists. If hydration is enabled, separately confirm the view is hydrated and ready; Angular does not guarantee that merely because afterNextRender ran.

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

Performance, reliability, and choosing an approach

Rendering a large DOM subtree at a high scale increases output dimensions and resource demands. Capture only the required element, avoid unnecessarily large virtual dimensions, and test slow images, long pages, and target devices. The documented image timeout default of 15000 milliseconds is a wait limit, not a performance promise. Browser canvas limits are device-dependent, and html2canvas’s selective CSS reconstruction means fidelity and successful export need to be verified for the actual page.

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

Choose based on the job: html2canvas is useful when the capture must happen in the user’s page and a DOM reconstruction is acceptable. If you need the browser’s rendered viewport rather than a reconstructed approximation, first confirm that a native browser or platform capture API is exposed in your target runtime; the html2canvas documentation does not establish that such an API is available to every ordinary web page. Also consider whether you need an element-only capture, how cross-origin resources are handled, and which browsers/runtime are supported.

Or skip the browser setup

If you need a screenshot of a URL rather than a canvas generated inside the Angular page, ScreenshotNeo provides a screenshot API and MCP server. Its capture flow accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot; each of those steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. AI agents can use its MCP tools, including take_screenshot, get_page_info, and capture_pdf.

One GET request can return an image or PDF. For example, using the supplied API call with the target URL changed to your own:

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 parameters and formats. Its free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. ScreenshotNeo is an option when you want URL-based captures without setting up browser-side rendering. Sign up for 1,000 free screenshots a month, with no card required.

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

Frequently Asked Questions

Does html2canvas return an image file?

No. Its Promise resolves to a canvas. Convert that canvas to a data URL or blob when you need an image file.

Can html2canvas capture content from a URL that is not open in the current page?

The method described here captures a DOM element in the current browser page. For a URL-based capture, use a service or runtime designed to load and capture that URL.

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.