Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
html2canvas

How to Fix “html2canvas Is Not Defined”

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

“html2canvas is not defined” means the JavaScript name is unavailable in the scope where your code calls it. In an npm or bundler project, install the package and default-import it in the same module that uses it. In a plain HTML page, load a valid browser build successfully before the calling script, and keep the scripts ordered. A failed request, an earlier script error, async execution, or module scoping can all leave the name unavailable.

What the error actually means

This is a JavaScript ReferenceError: execution reached a reference to html2canvas, but no variable with that name existed in the current scope. It does not, by itself, show that html2canvas is defective or that rendering has failed. First make the function available; only then investigate images, CSS, canvas dimensions, or screenshot fidelity.

The fix depends on how your page is built. There are two supported paths:

Project type Correct setup How availability is controlled
npm, bundler, or module source Install the package and import html2canvas from 'html2canvas'; in the module that calls it. The module dependency graph and its local bindings.
Standalone HTML Load a browser build with a successful script request before the caller. Script execution order and the browser global created by that build.

Fix an npm or bundler project

1. Install html2canvas in the project being built

From the directory that contains the application’s package manifest, run:

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

If you use workspaces, verify that the dependency was added to the workspace that produces the page containing the call. Installing it in a different directory does not make it resolvable by the current build.

2. Import the default export where you call it

Put the import in the source file that invokes the function:

import html2canvas from 'html2canvas';

async function captureCard() {
  const element = document.querySelector('#card');
  if (!element) throw new Error('Could not find #card');

  const canvas = await html2canvas(element);
  document.body.appendChild(canvas);
}

captureCard().catch(console.error);

The documented call shape is html2canvas(element, options). You can also use its Promise form directly:

html2canvas(document.body).then((canvas) => {
  document.body.appendChild(canvas);
});

An import is scoped to the importing module. It does not automatically create window.html2canvas, expose the name to an inline onclick, or make it available in another module. Move the call into the module that imports it, or explicitly design an interface between the module and the rest of the page.

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

3. Separate import errors from the ReferenceError

If the import line cannot be resolved, the browser console normally shows a build or module-loading error before your call runs. Fix that earlier error first. Check the package manifest, lockfile, bundler output, and the final browser console. Without those files and logs, the precise resolution problem cannot be identified, but the remedy is still to make the package part of the build that serves this page.

4. Do not assume an unrelated script can see the import

This arrangement does not work as many developers expect:

<script type="module" src="app.js"></script>
<button onclick="html2canvas(document.body)">Capture</button>

If app.js imports html2canvas, that imported binding remains inside the module. The inline handler has no variable named html2canvas. Attach the event listener and perform the call inside app.js instead:

import html2canvas from 'html2canvas';

document.querySelector('#capture').addEventListener('click', async () => {
  const canvas = await html2canvas(document.body);
  document.body.appendChild(canvas);
});

Fix a plain HTML page loaded with script tags

1. Use a valid built browser release

The html2canvas project documents downloading a built browser release for direct use. Select the current file from the project’s distribution or release information rather than copying an old, unverified filename. The available evidence does not establish a current CDN address or version, so do not treat an illustrative filename found in a snippet as a guaranteed path.

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

2. Make the dependency execute before your application

For ordinary classic scripts, the browser executes a script when it encounters it during parsing unless an attribute changes that behavior. A dependable deferred arrangement is:

<script defer src="path/to/html2canvas.browser.js"></script>
<script defer src="app.js"></script>

Replace the illustrative library path with the actual valid file you selected. Deferred scripts execute after parsing and retain document order, so app.js runs after the library script in this example.

3. Avoid async when order matters

async scripts execute as soon as each download finishes. Their order is therefore not guaranteed. If your application calls html2canvas as soon as it loads, an async dependency can produce the error intermittently: it works on one connection and fails on another. Remove async, use ordered defer, or start your application only after an explicit load signal.

4. Verify the request and the preceding console output

  1. Open Developer Tools and select the Network panel.
  2. Reload the page and locate the html2canvas script request.
  3. Confirm the request succeeds and returns the intended JavaScript file, not a 404 page, redirect, login page, or incompatible MIME response.
  4. In Console, look for a syntax, MIME, or runtime error before the “not defined” line. A preceding failure can prevent the library from creating its browser binding.
  5. Check that the caller’s URL and the dependency’s URL point to the files you actually deploy.

5. Keep module and global approaches distinct

If your page uses <script type="module">, prefer an import in that module and call the imported function there. Do not mix a module import with the expectation that an inline handler can use a global. Conversely, a browser build intended for a classic script may expose a global, but that behavior depends on the build you selected; confirm it in the project’s documentation and in the browser console.

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

A quick diagnosis decision tree

  • Error at the first call in bundled code: open the exact source module and verify that it contains the default import. Check that the package is installed in the workspace being built.
  • Error on a standalone HTML page: inspect the dependency request, then verify that the dependency script appears and executes before the caller.
  • Inline handler or separate classic script fails, but a module imported html2canvas: this is module scope, not a rendering problem. Move the call into the importing module.
  • Network or Console shows an earlier failure: fix that load, parse, or runtime error first. The missing binding may be only a downstream symptom.
  • The name now works but the output is wrong: stop debugging installation and investigate html2canvas rendering constraints.

When the identifier works but the canvas is still wrong

html2canvas reconstructs an image from the DOM and CSS information available to it; it does not capture a native browser screenshot. The project documents that the result may not exactly match the real visual representation because it builds a representation rather than taking an actual screenshot.

Cross-origin images

Images served from another origin can be restricted by browser canvas security rules. A successful function call does not guarantee that every remote image will appear. Check the image origin and the server’s cross-origin configuration after resolving the missing-name error.

Unsupported or incomplete CSS

html2canvas can render only the properties it understands. Differences in advanced CSS, filters, fonts, or browser rendering are output limitations, not evidence that the library failed to load.

Canvas dimensions and clipped content

Browsers impose canvas dimension limits, and very large or long elements may be clipped. The project FAQ recommends setting custom windowWidth and windowHeight when an element is cut off. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const canvas = await html2canvas(document.querySelector('#page'), {
  windowWidth: document.documentElement.scrollWidth,
  windowHeight: document.documentElement.scrollHeight
});

Use this only after confirming that the function itself is available; changing dimensions cannot repair a missing JavaScript binding.

Useful checks before changing code

  • Search the built page and source for spelling differences such as html2Canvas or html2canvas.js. JavaScript names are case-sensitive.
  • Confirm that the call runs after the DOM element exists. A missing element produces a different problem than an undefined function.
  • In a module project, inspect the generated bundle rather than assuming that an import in an unused file is included.
  • In a script-tag project, clear a stale service-worker or browser cache if the Network panel shows an old asset, then reload and verify the response again.
  • Do not “fix” the error by assigning an arbitrary empty function to window.html2canvas; that hides the load failure and produces misleading output.

Or skip the browser setup

If your goal is a reliable website image or PDF rather than running html2canvas in the page, ScreenshotNeo provides a server-side screenshot API. One request captures a URL without adding a browser dependency to your application.

Example with cURL (see the ScreenshotNeo documentation for parameters):

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)
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}`);

ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server lets Claude, Cursor, and other MCP clients use take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Sign up free for ScreenshotNeo.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Cost, reliability, and implementation choices

Use html2canvas when

  • The capture must happen in the user’s browser.
  • You need to capture a specific DOM element already rendered in your application.
  • Your assets are same-origin or otherwise configured for canvas access.
  • You accept that the result is a DOM reconstruction, not a native browser screenshot.

Use a screenshot API when

  • You want a backend job to capture pages without shipping browser setup to every client.
  • You need PDFs, full-page lazy-image loading, device presets, custom headers or cookies, waits, blocking rules, or batch capture.
  • You need explicit billing and failure status for automated workflows.

For ScreenshotNeo, every feature is available on every plan. Plans are Free (1,000 shots/month, no card), Starter ($5 for 3,000), Growth ($15 for 15,000), Pro ($39 for 60,000), Scale ($99 for 250,000), and Business ($249 for 1,000,000); annual billing provides two months free.

FAQ

Why does html2canvas work in one script but not another?

The scripts may have different scopes or execution timing. A module import is local to its module, while a separate classic script or inline handler cannot automatically see it. Script loading order can also vary when async is used.

Can I use the browser console to test the imported function?

Not necessarily. A module’s imported binding is not automatically a global console variable. Test from the importing module, or expose a deliberate debugging interface rather than assuming the name exists on window.

Does fixing the ReferenceError guarantee a pixel-perfect screenshot?

No. html2canvas has documented cross-origin image, CSS-support, and browser canvas-size constraints. Those affect the rendered result after the function is available.

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.

Frequently Asked Questions

Why does html2canvas work in one script but not another?

The scripts may have different scopes or execution timing. A module import is local to its module, while a separate classic script or inline handler cannot automatically see it. Script loading order can also vary when async is used.

Can I use the browser console to test the imported function?

Not necessarily. A module’s imported binding is not automatically a global console variable. Test from the importing module, or expose a deliberate debugging interface rather than assuming the name exists on window.

Does fixing the ReferenceError guarantee a pixel-perfect screenshot?

No. html2canvas has documented cross-origin image, CSS-support, and browser canvas-size constraints. Those affect the rendered result after the function is available.

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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.