ScreenshotNeo

BlogHow-to

How to Fix “html2canvas_1.default Is Not a Function” in Angular

Fix Angular’s html2canvas import error by matching the package export shape, compiler settings, and browser-only execution path.

By the ScreenshotNeo team30 September 20269 min read

How to Fix “html2canvas_1.default Is Not a Function” in Angular

Direct fix: html2canvas_1.default is not a function means your compiled Angular bundle is calling a .default export that is not callable at runtime. The usual cause is an import/export shape mismatch between html2canvas, TypeScript interop settings, Angular CLI, and the generated module format. Match the import to the package shape, rebuild the Angular app, and call html2canvas only in a browser component after the target element exists.

For a CommonJS-style build or older compiler interop, start with:

import * as html2canvas from 'html2canvas';

html2canvas(element).then(canvas => {
  // use the canvas
});

If your installed version exposes a true default export and your compiler is configured for it, use:

import html2canvas from 'html2canvas';

html2canvas(element).then(canvas => {
  // use the canvas
});

Do not switch between these forms randomly. A namespace import is an object containing exports; a default import binds the module’s default export. The runtime error occurs when the generated code expects the latter but receives the former. The original regression was reported after an Angular CLI upgrade in html2canvas issue #1440 (maintainer issue).

Why this error happens

html2canvas is a browser-side DOM renderer. Its README describes a process that reads the DOM and applied styles, then reconstructs the result as a canvas image. The documented API is html2canvas(element[, options]) and returns a Promise resolving to a <canvas> element (html2canvas README).

TypeScript has two distinct import meanings:

Import Runtime expectation Typical fit
import html2canvas from 'html2canvas' The module has a callable default export. True ESM default export with compatible compiler and bundler settings.
import * as html2canvas from 'html2canvas' The binding is a namespace object containing exports. CommonJS or older interop output where the callable export is exposed through the namespace.

MDN documents that namespace imports expose a module namespace object, while default imports bind the module’s default export (MDN import reference). Angular CLI, TypeScript, and the package version can change the generated wrapper, so an import that worked before an upgrade can fail without any change to your capture code.

Repair the import step by step

  1. Record the versions. Save the Angular CLI version, Angular version, TypeScript version, html2canvas version, package manager, and the relevant lockfile entry. A regression diagnosis is much easier when the complete toolchain is known.
  2. Confirm one installation. Check package.json and the lockfile for duplicate html2canvas versions. Remove stale or nested copies if your dependency tree contains more than the application expects.
  3. Inspect the current import. If the stack trace contains html2canvas_1.default and the value is not callable, remove the default import and try the namespace form shown above.
  4. Let TypeScript guide the choice. If the namespace form produces “This expression is not callable,” use the package’s supported default export with compatible compiler settings. Do not silence the error with any; that hides the shape mismatch.
  5. Restart the development server. Stop and restart ng serve after changing the import so the bundle and dependency graph are rebuilt.
  6. Verify in a browser-only path. Call the function after the view has rendered and only where window and document exist.
html2canvas reconstructs a browser DOM element into a canvas and depends on browser rendering and same-origin access.
html2canvas reconstructs a browser DOM element into a canvas and depends on browser rendering and same-origin access.

A complete Angular component example

This example captures a template element after the view is available, converts the canvas to a PNG, and reports failures. Choose one import form; the example uses the namespace form for CommonJS-style interop.

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import * as html2canvas from 'html2canvas';

@Component({
  selector: 'app-card-capture',
  template: `
    <section #captureTarget class="card">
      <h1>Angular card</h1>
      <p>This element will be rendered to a canvas.</p>
    </section>
    <button type="button" (click)="capture()">Download PNG</button>
  `,
  styles: [`
    .card { width: 640px; padding: 24px; background: white; color: #172033; }
  `]
})
export class CardCaptureComponent implements AfterViewInit {
  @ViewChild('captureTarget') target!: ElementRef<HTMLElement>;
  private viewReady = false;

  ngAfterViewInit(): void {
    this.viewReady = true;
  }

  async capture(): Promise<void> {
    if (!this.viewReady || !this.target?.nativeElement) {
      throw new Error('Capture target is not ready');
    }

    try {
      const canvas = await html2canvas(this.target.nativeElement, {
        backgroundColor: '#ffffff',
        useCORS: true,
        logging: false,
        scale: Math.min(window.devicePixelRatio || 1, 2)
      });

      const link = document.createElement('a');
      link.download = 'angular-card.png';
      link.href = canvas.toDataURL('image/png');
      link.click();
    } catch (error) {
      console.error('html2canvas capture failed', error);
    }
  }
}

If your project uses the default export successfully, change only the import:

import html2canvas from 'html2canvas';

TypeScript and Angular configuration checks

Review the effective compiler configuration rather than assuming the root tsconfig.json is the one used by the browser build. Angular projects commonly extend another file. Check the tsconfig.app.json chain and the Angular builder configuration.

  • esModuleInterop and allowSyntheticDefaultImports: These options affect how TypeScript accepts and emits default-style imports for CommonJS modules. They do not magically turn a namespace object into a function at runtime.
  • module: The emitted module target influences the wrapper Angular and the bundler generate.
  • Angular CLI version: An upgrade can alter webpack/esbuild handling or dependency optimization, exposing a previously hidden mismatch.
  • Lockfile consistency: Install from the lockfile in CI and after deleting node_modules so the same html2canvas version is used.

Use the package’s documented export shape for the version you installed. Avoid deep imports into internal files: they are more likely to break when the package changes its build layout.

Browser timing, SSR, and lifecycle

Fixing the import only makes the function callable. html2canvas still needs a real browser DOM. Do not invoke it from an Angular server-side rendering route, a Node process, a build script, or a service that runs before the component view exists.

Safe timing checklist

  • Use AfterViewInit, a click handler, or another point after the target element is rendered.
  • Guard browser-only code when using SSR. For example, inject Angular’s PLATFORM_ID and call isPlatformBrowser before accessing window or document.
  • Wait for images, web fonts, and asynchronous data that affect layout before capture.
  • Capture the element itself, not a stale ElementRef from a destroyed view.
import { isPlatformBrowser } from '@angular/common';
import { Inject, PLATFORM_ID } from '@angular/core';

constructor(@Inject(PLATFORM_ID) private platformId: object) {}

canCapture(): boolean {
  return isPlatformBrowser(this.platformId) && !!this.target?.nativeElement;
}

When the import works but the image is wrong

html2canvas reconstructs pixels from DOM and CSS; it is not a native browser screenshot. Some CSS properties, browser rendering details, plugins, and cross-origin resources may not reproduce exactly.

Images or fonts are missing

Cross-origin content is the most common cause. The README explains that cross-origin resources need a proxy to bring them to the same origin. Configure the image server with appropriate CORS headers, use same-origin assets, or provide a proxy. useCORS: true helps only when the remote server permits the request; it cannot override browser security.

The capture is blank or clipped

  • Confirm the target has non-zero dimensions and is visible when capture begins.
  • For a long page, capture a specifically sized wrapper and check overflow and fixed-position elements.
  • Wait for async content and images before calling html2canvas.
  • Reduce the scale or target size if the browser cannot allocate a canvas large enough.

Fonts or layout differ

Wait for document.fonts.ready where supported, ensure the font stylesheet is loaded, and capture after Angular finishes rendering data-bound content. Browser zoom, device pixel ratio, and responsive breakpoints can change the result.

Troubleshooting table

Symptom Likely cause Fix
html2canvas_1.default is not a function Default import does not match the runtime export. Try the namespace import, or use the supported default export with compatible compiler settings. Rebuild.
“This expression is not callable” TypeScript sees a namespace object. Use the package’s default export if that version provides one; do not cast to any.
document is not defined Code ran during SSR or in Node. Move capture to a browser-only lifecycle path and guard with isPlatformBrowser.
Images taint the canvas or disappear Cross-origin resources lack permission. Use same-origin assets, configure CORS, or use a proxy.
Capture runs before content appears Angular view, data, image, or font is not ready. Capture after rendering and wait for required resources.
Works locally, fails in production Different lockfile, optimizer, module target, or dependency version. Compare built versions and effective tsconfig; install deterministically from the lockfile.

Performance and reliability considerations

Canvas rendering uses browser CPU and memory. Large DOM trees, high device-pixel-ratio scales, shadows, filters, and very tall documents increase work and can exceed canvas limits. Capture the smallest meaningful element, cap scale, avoid repeated captures during rapid input, and debounce resize or scroll handlers.

For reliable downloads, create the object or data URL only after the Promise resolves and release object URLs when they are no longer needed. Treat a client-side capture as best effort: browser extensions, privacy settings, network failures, CORS, and browser differences can affect output.

Converting the result to a PDF

html2canvas returns a canvas, not a PDF. A PDF workflow needs another browser library to place the canvas image on one or more pages. For long content, split the rendered result into page-sized sections and account for image quality, margins, and memory. If you need server-side PDF rendering, a browser automation service is generally a better fit than running html2canvas in Node; the project README says html2canvas is not suitable for Node.js.

A hosted screenshot flow can remove consent banners, popups and chat widgets before billing for a clean shot.
A hosted screenshot flow can remove consent banners, popups and chat widgets before billing for a clean shot.

Or skip the browser setup

If your goal is a clean screenshot of a URL rather than a DOM element inside your Angular app, ScreenshotNeo handles the browser capture for you. See the ScreenshotNeo API documentation for all options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and whether it was billed. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account to get started.

FAQ

Should I always use import * as html2canvas?

No. Use it when your installed package and emitted module format expose a callable CommonJS-style export through the namespace. Use a default import when the package exposes a true default export and your compiler and bundler support it.

Is this error caused by Angular templates?

Usually no. The exception is raised before rendering because the imported runtime value is not callable. Template timing can cause separate errors after the import is corrected.

Can I run html2canvas in a Node service?

No. The project describes it as browser dependent and not suitable for Node.js. Use it in a browser, or use a server screenshot API such as ScreenshotNeo for URL captures.

Does useCORS bypass cross-origin restrictions?

No. The remote resource must still return headers that allow the browser request, or you need same-origin hosting or a proxy.

Why did an Angular upgrade expose the problem?

An upgrade can change TypeScript output, bundler interop, dependency optimization, or the resolved html2canvas version. Compare those versions and the generated module behavior when diagnosing the regression.